Home > Blockchain >  How to type link prop in component (React TypeScript)?
How to type link prop in component (React TypeScript)?

Time:11-09

I'm fairly new to TypeScript and I've been struggling with this for a bit now.

I would like to pass on routes to a component as a prop, but I don't know how to type it, so I keep getting TypeErrors from TypeScript.

ParentComponent (where I pass on the routes):

import { ChildComponent } from '../components';

export const ParentComponent = () => (
  
  <div>
    ...
    <ChildComponent to={"/page_one"}>text</ChildComponent>
    <ChildComponent to={"/page_two"}>text</ChildComponent>
    <ChildComponent to={"/page_three"}>text</ChildComponent>
    ...
  </div>
)

And then my child component looks like this:


  import { Link } from 'react-router-dom';

  interface ChildProps {
  children: React.ReactNode
  to?: React.LocationDescriptor<any> 
  }

  export const ChildComponent = ({children, to}): ChildProps => {
   
    ...
    <Link to={to}/>
    {children}
    ...

  }

I keep getting the Error: "... is not assignable to type 'LocationDescriptor | ((location: Location) => LocationDescriptor)'."

I have tried multiple ways to type it and have searched around, but couldn't find any solution that worked for me.

So, what's the correct way to type the 'to' prop?

CodePudding user response:

As far as I know keeping the type as string would solve the matter

type Props = { to: string; };

Also remove the question mark to make sure that the value is always passed. For some reason if the value you might get can be undefined, add a check or default value to it.

Hope this answers your query.

  • Related