turtle
turtle

Reputation: 8073

How to pass props to route in react router v5 with Typescript?

I have a route that looks like this, which renders just fine:

<Route
  exact={true} 
  path="/"
  render={() => {
    return <Home />
  }}
/>

If I add in any prop

<Route
  exact={true}
  path="/"
  render={() => {
    return <Home foo="bar" />
  }}
/>

I get the following warning:

Type '{ foo: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'foo' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'. TS2322

How can I pass props to a component with Typescript?

My Home component looks like this:

type homeType = {
  foo: string
}

const Home: React.FC = ({ foo }: homeType) => { 
  return <p>{foo}</p>
}

Upvotes: 3

Views: 3503

Answers (1)

Richard Price
Richard Price

Reputation: 490

Your home component needs to be defined with the props which will be sent to it, i.e.

import React from 'react';

type CardProps = {
  title: string,
  paragraph: string
}

export const Card = ({ title, paragraph }: CardProps) => 
<aside>
  <h2>{ title }</h2>
  <p>
    { paragraph }
  </p>
</aside>

const el = <Card title="Welcome!" paragraph="To this example" />

So with your example i presume you have a component called Home, which should be defined as such

type HomeProps = {
  foo: string
}

export const Home= ({ foo }: HomeProps) => 
  <h2>{ foo }</h2>


Upvotes: 2

Related Questions