A guide on resolving a Typescript error when using next/link element in Next JS

When working on my code, I encountered a Typescript error that's bothering me:

Type 'string' is not assignable to type 'RouteOrQuery'.ts(2322) nextjs-routes.d.ts(32, 5): The expected type comes from property 'href' which is declared here on type 'IntrinsicAttributes & LinkProps & { children?: ReactNode; }'

The issue is specifically related to the href parameter of the <Link> element.

import * as React from 'react';
import Link from 'next/link';
import styles from './breadcrumbs.module.css';

interface iMajors {
    theatre: string;
    musicaltheatre: string;
    opera: string;
    dance: string;
    music: string;
    visualarta: string;
}

type Props = {
    schoolName: string;
    major: string;
    slug: string;
};

const Breadcrumbs: React.FC<Props> = (props) => {

    const {
        schoolName,
        major,
        slug
    } = props;

    const majors: iMajors = {
        theatre: `Theatre`,
        musicaltheatre: `Musical Theatre`,
        opera: `Opera`,
        dance: `Dance`,
        music: `Music`,
        visualarts: `Visual Arts`
    };

    if (schoolName && major && slug) {
        return (
            <div className={styles.container}>
                <nav>
                    <ul>
                        <li><Link href="/">Home</Link></li>
                        <li><Link href={`/${major}`}>{majors[major as keyof typeof majors]}</Link></li>
                        <li><Link href={`/${major}/${slug}`}>{schoolName}</Link></li>
                    </ul>
                </nav>
            </div>
        );
    }

    return null;

};

export default Breadcrumbs;

Answer №1

The issue lies within the type generated by nextjs-routes in the nextjs-routes.d.ts file. For guidance on the correct format for the href attribute, refer to their ReadMe (https://www.npmjs.com/package/nextjs-routes).

Here's an example of how to use the href attribute with an optional query parameter:

<li><Link href={{pathname: "/", query: {foo: "test"}}}>{majors[major as keyof typeof majors]}</Link></li>

If you make changes to your paths, remember to regenerate the nextjs-routes.d.ts file using npx nextjs-routes. The file also includes the Route type, which outlines the acceptable pathnames that can be used.

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

Leveraging the power of the map function to manipulate data retrieved

I am working on a nextjs app that uses typescript and a Strapi backend with graphql. My goal is to fetch the graphql data from strapi and display it in the react app, specifically a list of font names. In my react code, I have a query that works in the p ...

Trouble with Nested Routing in React Router Version 6: Route not Rendering

I'm facing issues nesting a path within another path in react-router-dom version 6. When I try to visit the nested argument's page (/blog/1), it shows up as a blank non-styled HTML page. However, when I add a child path to the root like /blog, it ...

Trouble arises when attempting to modify a property inherited from a parent class in TypeScript while

I've defined a base class like the following: import Vue from "vue"; class ComponentBase extends Vue { constructor() { super(); this.left = 100; this.top = 100; this.isSelected = false; } public left: numb ...

Tips for Handwriting combineReducer using Typescript?

Learning redux with typescript has been quite a journey for me. I've successfully implemented combineReducers in my code: export const reducerBase= combineReducers({ stateA: reducerA, stateB: reducerB, stateC: reducerC }); Everything was going ...

Obtain a Spotify Token and showcase information in next.js

This is a Simple Next.js component designed to display the currently playing song on Spotify. Context: Utilizing app Router Due to Spotify's token requirements necessitating a server-side call, the entire request is made to fetch the song from an ...

Is there a way to combine Vue3, Stripe, and Typescript for seamless integration?

I am currently developing a Vue3 application and running into some issues while trying to integrate Stripe. I am facing difficulty in incorporating it successfully. Here is the code snippet from my Vue3 component named Checkout.vue: <template> .... ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

Beware of potential issues with FontAwesomeIcon when incorporating it into a Typescript file

I'm currently working with NextJS and Typescript. I encountered an issue when trying to import FontAwesomeIcon like this <FontAwesomeIcon icon={faCheck as any} /> as it triggered a warning in the console stating "Warning: FontAwesomeIcon: Suppor ...

Successfully upgraded Angular 7 to 8, however, encountering an issue with the core not being able to locate the rxjs module

After updating my Angular version from 7.X to 8.2.5, everything seemed fine until I started getting errors related to the rxjs module within the angular/core package. Despite having the latest version of rxjs (6.5.3), the errors persisted even after removi ...

Issue with Vue property's sub-object not inheriting methods from prototype

Incorporating Vue into my project to showcase an intricate hexagonal grid has been quite challenging. Utilizing the Honeycomb library for handling the grid data in memory has proven to be both beneficial and complex. The library introduces a specialized Gr ...

Converting enum flags to strings

I'm encountering an issue with converting enum flags to strings and parsing them. Here is an example of my enum: enum CookieOptions { None = 0, Necessary = 1 << 0, Analytical = 1 << 1, Marketing = 1 << 2, Personalization = ...

Angular auto-suggest components in material design

Can someone assist me in resolving my issue? I am trying to incorporate an autocomplete feature with a filter into my form. .ts file : contactArray; selectedContact: IContact; myControl = new FormControl(); filteredContact: Observable<string[] ...

How can I effectively test the success of a form submission in next.js using jest for unit testing?

At the moment, I am in the process of developing a unit test for a registration form within my application. The main objective of this test is to ensure that the registration process can be executed successfully without actually saving any new data into th ...

The sticky navbar fails to stay in place when the content becomes too lengthy

This is my current state of code (minified, for explanation only) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-w ...

Updating a value in an array in Angular using the same ID

I have an array of buildings that looks like this: const buildings = [ { id: 111, status: false, image: 'Test1' }, { id: 334, status: true, image: 'Test4' }, { id: 243, status: false, image: 'Test7' }, { id: 654, stat ...

Having trouble with rendering routes in Next.js?

Encountering an error with next.js routing for non-hash routes. Some have suggested that adding a hash to the query could cause this issue. Error: Cancel rendering route Has anyone experienced this issue before and know how to resolve it? It appears to be ...

Encountered an issue when trying to generate a video from a canvas using FFmpeg W

I'm currently utilizing ffmpeg.wasm within my Next.JS application. Below are the specifications: "@ffmpeg/ffmpeg": "^0.12.5", "@ffmpeg/util": "^0.12.0", "next": "^13.0.6", "react": ...

How can I make sure that another function will only be executed after the completion of a function in

I'm currently working on an app with Angular CLI, and I am trying to retrieve a list after an insertion. Despite trying various methods such as observer, promise, async, setTimeout, etc., I haven't been able to find the right solution yet. I feel ...

What is the process for transforming a Typescript source file into JavaScript?

I have a basic HTML file with a script source set to index.ts. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge ...

Issue: Module 'stylelint' not found in Angular Project

I've been attempting to execute this command to validate all of the .scss files (and even tried with .css files) and I keep encountering this error. $ stylelint "apps/**/*.scss" It worked once before but not anymore, even after restarting my compute ...