3

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>
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
turtle
  • 7,533
  • 18
  • 68
  • 97
  • 2
    Looks like this has nothing to do with React Router, can you post your `Home` component? – QoP Jan 08 '20 at 18:23
  • Does this answer your question? [react-router - pass props to handler component](https://stackoverflow.com/questions/27864720/react-router-pass-props-to-handler-component) – Richard Price Jan 08 '20 at 18:32
  • Thanks, but no it does not. i can't even pass a static string like `foo` in my example. – turtle Jan 08 '20 at 20:04
  • 1
    It seems like this is what I need, but it's far far too difficult for me to understand: https://medium.com/@robjtede/the-real-routewithprops-react-component-in-typescript-defacde01991 – turtle Jan 08 '20 at 20:28

1 Answers1

2

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>


Richard Price
  • 482
  • 4
  • 13