wc203
wc203

Reputation: 1217

Passing Props to a Component in React Routing

Can you explain what this line? What props and {...props} does ?

<Route exact path='/' render={props => <Home {...props} />} />

Upvotes: 2

Views: 3742

Answers (3)

Meet Zaveri
Meet Zaveri

Reputation: 3059

Explanation

TLDR; Those props passed in render indicate as route-props which provides you match,location and history objects through which you can route through components or utilize those objects way you want in child components(if passed through props).

{...props} just supplies all the properties it has in object. ... is known as spread syntax which helps to get all the existing properties in the object mentioned(here props). Like passing down the data component don't need it now but will be required by children through current component structure.

Here {...props} will yield to match,location and history passed to component in render

React Router API

Source - https://reacttraining.com/react-router/web/api/Route/render-func

Route props

All three render methods will be passed the same three route props

  • match
  • location
  • history

Render (function)

Instead of having a new React element created for you using the component prop, you can pass in a function to be called when the location matches. The render prop receives all the same route props as the component render prop.

Those props are internal API of react-router v4. You can see more about render method of <Route> component

If you pass a component and those props in that component(child), you can log the props and you'll find all of the three props provided by route-props

Props in child (if you log in console in child component) : Object {match: Object, location: Object, history: Object, staticContext: undefined}

Example

You can find example codesandbox I have curated just for this example - https://codesandbox.io/embed/0m1z1xwxnw

Alternative

If you don't want to use render to internally render component you want, you can use withRouter HOC and wrap your component into that HOC as export default withRouter(WrappedComponent) and it will provide all three objects you want i.e. match,location and history and hence appending it into props object

Upvotes: 5

Tholle
Tholle

Reputation: 112777

...props is called the spread syntax and is used to pass every property in the props object as a separate prop to the Home component.

It might be easier to see why this works if you compiled the JSX to React.createElement calls.

React.createElement(Home, {
  ...props
});

const obj = {
  foo: 'foo',
  bar: 'bar'
};

const props = {
  baz: 'baz',
  ...obj
};

console.log(props);

Upvotes: 1

Klaudia692
Klaudia692

Reputation: 21

Try put your props in brackets, just like this: <Route exact path='/' render={(props) => <Home {...props} />} />

Upvotes: 0

Related Questions