Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing props to component in React Router 4

Tags:

I am new to react-router and I just started writing an app using react-router V4. I would like to to pass props to components rendered by <Match /> and I am wondering about what's the 'best' or 'proper' way to do so.

Is it by doing something like this?

<Match pattern="/" render={
    (defaultProps) => <MyComponent myProp = {myProp} {...defaultProps} />
}/>

Is this (passing props to components to be rendered by <Match />) even a good practice to do so with react-router or is it an antipattern or something; and if so, why?

like image 357
Dimitris Karagiannis Avatar asked Oct 05 '16 10:10

Dimitris Karagiannis


People also ask

How do I pass Props to component in react router?

If you are using react-router v4, you can pass it using the render prop. Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.

What route props does react router give you access to?

The render prop function has access to all the same route props (match, location and history) as the component render prop. import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Router, Route } from "react-router-dom"; // convenient inline rendering ReactDOM.

Can we pass props to the parent component?

To pass data from a child component to its parent, we can call a parent function from the child component with arguments. The parent function can be passed down to the child as a prop, and the function arguments are the data that the parent will receive.

How do I pass props from one page to another in react?

There is no way in React to set props (even though it was possible in the past). After all, props are only used to pass data from one component to another component React, but only from parent to child components down the component tree.


1 Answers

You must use the render prop instead of component to pass on custom props, otherwise only default Route props are passed ({match, location, history}).

I pass my props to the Router and child components like so.

class App extends Component {

  render() {
    const {another} = this.props
    return <Routes myVariable={2} myBool another={another}/>
  }
}

const Routes = (props) =>
  <Switch>
    <Route path="/public" render={ (routeProps) => 
      <Public routeProps={routeProps} {...props}/>
    }/>
    <Route path="/login" component={Login}/>
    <PrivateRoute path="/" render={ (routeProps) =>
       ...
    }/>
  </Switch>
like image 120
Qwerty Avatar answered Oct 16 '22 22:10

Qwerty