Amir
Amir

Reputation: 192

React Router pass route parameter from parent to child

Hi I have created a wrapper around the Route component in react called PrivateRoute.

I want to be able to call a Page component from inside of this and pass the :id of the path to it, so this is how i call it:

 <PrivateRoute exact path="/page/:id"
   render={() => <Page secure={true} resource="/pages/" />}/>

But inside of the Page component where i want to access the route param.

  componentDidMount() {
    this.getEntity(this.props.match.params.id);
  }

this.props.match.params.id shows as undefined.

Previously i had this:

<PrivateRoute path="/pages/:id" component={Page} />

and Page received the id. via this.props.match.params.id but then i don't know how i can pass other props to the page which is why i changed it.

This is the implementatio of my Route wrapper

class PrivateRoute extends React.Component {
  render() {
    const { isLoggedIn, children, ...rest } = this.props;
    const loggedIn = localStorage.getItem('loggedIn');
    if (loggedIn == "true") {
      return <Route {...rest}>{children}</Route>;
    } else {
      return (
        <Redirect
          to={{
            pathname: "/login",
            state: { referrer: this.props.location }
          }}
        />
      );
    }
  }
}

Does anyone know how i am supposed to do this?

Thanks

Upvotes: 0

Views: 2762

Answers (1)

Branislav Lazic
Branislav Lazic

Reputation: 14806

Ask yourself: "What's 'this'?". In the context of:

componentDidMount() {
  this.getEntity(this.props.match.params.id);
}

this.props doesn't belong to properties coming from PrivateRoute component.

Solution:

Add prop id to Page component and pass the id like this:

<PrivateRoute exact path="/page/:id"
   render={({ match }) => <Page secure={true} resource="/pages/" id={match.params.id} />}/>

Upvotes: 1

Related Questions