Typescript navigation and Next.js technology

Currently, I am in the process of learning typescript and attempting to create a navigation bar. However, I encountered an error message stating "Unexpected token header. Expected jsx identifier".

I am a bit puzzled by this issue. Could someone kindly provide some guidance on where the problem might lie?

This is the content of Navbar.tsx file:


  import Link from "next/link";
import React, { useState } from "react";
import NavItem from "./NavItem";

export interface INavbar {
  navActive: boolean;
  
}


const Navbar: React.FC<INavbar> = (className, ...navProps) => {

  const [navActive, setNavActive] = useState(null);
  const [activeIdx, setActiveIdx] = useState(-1);
  
const MENU_LIST :{ text: string, href: string}[] = [
    { text: "Home", href: "/" },
    { text: "About Us", href: "/about" },
    { text: "Contact", href: "/contact" },
  ];
 
  return (

    
    <header>
      <nav className={`nav`}>
        <Link href={"/"}>
          <a>
            <h1 className="logo">KT</h1>
          </a>
        </Link>

        <div
          onClick={() => setNavActive(!navActive)}
          className={`nav__menu-bar`}
        >
       
        </div>
        <div className={`${navActive ? "active" : ""} nav__menu-list`}>
          {MENU_LIST.map((menu, idx) => (
            <div
              onClick={() => {
                setActiveIdx(idx);
                setNavActive(false);
              }
              key={menu.text}
            >
              <NavItem active={activeIdx === idx} {...menu} />
            </div>
          )
        </div>
      </nav>
    </header>  
}

export default Navbar;

In addition, here is the content of Navitem.tsx file:

import Link from 'next/link';

export interface INavItem {
  text: string;
  href: string;
  active: boolean;
}

const NavItem: React.FC<INavItem> = ({ text, href, active }) => {
  return (
    <Link href={href}>
      <a className={`nav__item ${active ? 'active' : ''}`}>{text}</a>
    </Link>
  );
};

export default NavItem;

Answer №1

It appears that there are some missing parentheses/brackets in your Navbar code structure:

              }} <--- Added a bracket here
              key={menu.text}
            >
              <NavItem active={activeIdx === idx} {...menu} />
            </div>
          ))} <--- Added a parenthesis and a bracket
        </div>
      </nav>
    </header>  
)} <--- Added a parenthesis

An additional issue is that the props passed to the component are treated as a single object, whereas in `Navbar`, they are being used as if multiple objects were passed.

To resolve this, consider changing:

const Navbar: React.FC<INavbar> = (className, ...navProps) => {

to:

const Navbar: React.FC<INavbar> = ({className, ...navProps}) => {

This adjustment ensures proper utilization of the `INavbar` interface. However, since `className` is not expected in `INavbar`, you can either include `className` in `INavbar` or remove it from props deconstruction. As `className` is unused, removing it seems appropriate:

const Navbar: React.FC<INavbar> = ({...navProps}) => {

While we are utilizing `navActive`, `navProps` remain unused, allowing us to refine the destructured props further:

const Navbar: React.FC<INavbar> = ({ navActive }) => {

Seemingly, you intend to use `navActive` as a prop and define it using `useState`. Since both actions conflict, choose either option—set `navActive` as a state variable or a prop. Assuming setting it as a prop is preferred, you should delete this line:

const [navActive, setNavActive] = useState(null);

To eliminate the error related to 'setNavActive', introduce its definition. Given that 'navActive' is a prop, 'setNavActive' must also be included as a prop:

export interface INavbar {
  navActive: boolean;
  setNavActive: (value: boolean) => void;
}

const Navbar: React.FC<INavbar> = ({ navActive, setNavActive }) => {

Note the typing for 'setNavActive' as `(value: boolean) => void` in our `INavBar`. This specifies that 'setNavActive' expects a boolean parameter named 'value'.

By adding 'setNavActive' as an anticipated prop, TypeScript now assists by flagging where 'Property 'setNavActive' is missing' when `` is utilized.

When implementing `Navbar`, ensure 'navActive' and 'setNavActive' are provided as props as follows:

<Navbar navActive={navActive} setNavActive={setNavActive} />

In the same component, establish 'navActive' and 'setNavActive' through `useState`. We shall initialize 'navActive' with 'false', given its boolean nature:

const [navActive, setNavActive] = useState(false);

Although these adjustments may seem complex, they aim to provide clarity. To observe all recommended changes at once, refer to the comprehensive example on CodeSandbox where the entire setup is demonstrated: https://codesandbox.io/s/zen-oskar-qi81gk?fontsize=14&hidenavigation=1&theme=dark

Answer №2

It appears that the closing parenthesis is missing in the return statement

return (
  <header>
   ...
  </header>
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An issue occurred during the construction of an angular project: The Tuple type '[]' with a length of '0' does not contain any elements at index '0'

When I run the command ng build --prod, I encounter the following error: ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index &apo ...

Sorting through items based on several URL parameters

In an effort to be concise yet clear, I am working on an ecommerce website using Next.js and Shopify. This site features products that need to be filterable based on certain attributes. I retrieve products from the Shopify API, each with its own Product Ty ...

What are the steps to installing Typescript on my computer?

npm ERROR! encountered code EACCES during installation npm ERROR! while trying to create a directory npm ERROR! at path /usr/local/lib/node_modules/typescript npm ERROR! with error number -13 npm ERROR! Error: EACCES: permission denied, mkdir '/usr/lo ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Eliminate properties from a TypeScript interface object

After receiving a JSON response and storing it in MongoDB, I noticed that unnecessary fields are also being stored in the database. Is there a way to remove these unnecessary fields? interface Test{ name:string }; const temp :Test = JSON.parse('{ ...

Creating a dynamic sitemap in Next.js using the sitemap package: A step-by-step guide

In my web application, I am using Next.js and Back4App. Recently, I came across the sitemap library to generate a sitemap for my website. However, I have encountered difficulties in creating a dynamic sitemap as I am unable to execute any API calls or clou ...

Using Typescript to remove an element from an array inside another array

I've encountered an issue while trying to remove a specific item from a nested array of items within another array. Below is the code snippet: removeFromOldFeatureGroup() { for( let i= this.featureGroups.length-1; i>=0; i--) { if( this.featureGr ...

Encountered a 404 error (not found) while making a GET request with axios

I encountered an issue with my pizza shop application built with Next.js. Whenever I run the app on my computer, I come across this error: https://i.sstatic.net/tsQzZ.png The error disappears after refreshing the page. Here is my index.js file: import ax ...

Connecting HTML to an AngularFirestore collection using snapshotChanges

In my mobile app, I am using AngularFirestore2v5/rxjs to connect a hybrid Ionicv3/Angularv4 app to a Firestore collection. While binding UI with AngularFirestore.valueChanges works fine, switching to snapshotChanges for retrieving the id is causing some is ...

When attempting to utilize expo-av in a React-Native project on iOS, the recorded MP4 file encountered an issue when trying to submit it as form data for Open

I've been working tirelessly through the night, trying to record myself on my iPhone using expo-av to capture speech and then upload it to openai's transcriptions endpoint with the whisper-1 model. The recording is saved as an mp4 file, which I ...

Is it possible to record the attributes within an interface in TypeScript?

Imagine I have the following scenario: interface Validator { validate: (value: string) => boolean; errorMessage: string; } interface EditDialogField { label: string; prop: string; required?: boolean; type: 'input'; validators?: ...

Changing state in one component from another component

I am attempting to replicate a similar sidebar feature in NextJS, inspired by this original sidebar. To achieve this, I have created two components: First, a component for the menu button: export default function MobileMenuBtn() { return ( <div cl ...

Angular 6: A class with no 'default' modifier must explicitly specify a name

I am encountering this error in my ts.file, as I delve into the world of Angular/Ionic. Can anyone help identify the possible reasons for this? I have attempted multiple solutions to address it, but unfortunately, none have proven successful. import { Co ...

Using dynamic loading in NextJS, how can one access the ReactQuill Ref?

Currently facing an interesting issue. I am making use of NextJS for its server-side rendering abilities and incorporating ReactQuill as a rich-text editor. To work around ReactQuill's connection to the DOM, I am dynamically importing it. However, thi ...

The Unhandled Promise Rejection Warning in mocha and ts-node is due to a TypeError that arises when attempting to convert undefined or null values

I've been encountering issues while setting up ts-node with mocha, as the test script consistently fails. I attempted to run the following commands: mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ ...

Cleaning up HTML strings in Angular may strip off attribute formatting

I've been experimenting and creating a function to dynamically generate form fields. Initially, the Angular sanitizer was removing <input> tags, so I discovered a way to work around this by bypassing the sanitation process for the HTML code stri ...

Creating a message factory in Typescript using generics

One scenario in my application requires me to define message structures using a simple TypeScript generic along with a basic message factory. Here is the solution I devised: export type Message< T extends string, P extends Record<string, any> ...

Why won't NextJS Image elements render on iOS 16 when they are not in the viewport initially?

I opted to implement NextJS for enhanced routing capabilities and image optimization. However, I encountered an issue with certain images failing to load properly on iOS devices. The problem arises within a scrollable horizontal container featuring Product ...

Sharing information with a service in Ionic and Angular

I need to send data to my service and incorporate it into a URL string. The code snippet below shows how I am obtaining the data in my constructor when the user navigates to the page: constructor(public alertController: AlertController, pri ...

The justify-content property is failing to properly align content along the main axis in Grid layout

I've implemented tailwind for my CSS styling. Within a simple div, I have 3 child elements. My goal is to create space between them along the main axis. Here's the code snippet in question: <div className="grid grid-cols-12 text-white ju ...