4

I'm using react-router-dom and generate my routes dynamically from an array like so

Routes Data

const routes = [
  {
    path: '/',
    exact: true,
    component: () => <MyComponent />
  }
}

Route Generation

{routes.map((route, index) => {
  return <Route
    key={index}
    path={route.path}
    exact={route.exact}
    component={route.component}
  />
})}

Render Prop I found out about the render() prop I could define but even so how do I do this since the component is inside a variable

const props = this.props;
{routes.map((route, index) => {
  return <Route
    key={index}
    path={route.path}
    exact={route.exact}
    render={(props) => <??? {...props} />
  />
})}

How can I pass this.props during the route generation?

1 Answer 1

3

You could change your array to just include the component instead of a new function component that renders the component and you will get the props sent to it:

const routes = [
  {
    path: '/',
    exact: true,
    component: MyComponent
  }
}

You can use any capitalized variable as a component, so you could also do this if you prefer:

{routes.map((route, index) => {
  const Component = route.component;

  return <Route
    key={index}
    path={route.path}
    exact={route.exact}
    render={(props) => <Component {...props} />
  />
})}
Sign up to request clarification or add additional context in comments.

3 Comments

ah thank you Tholle this is great! How would you handle the redirect cases? For instance my array in my actual implementation has some routes objects where the component is a redirect such as { path: '/', exact: true, component: <Redirect to='/other/route' /> }, I'm thinking maybe add an extra field redirect: '/other/route' to my routes object and then in my loop do a condition if that was defined?
@Newton You're welcome! For that the second approach might be best. { component: MyComponent } for regular components, and { component: () => <Redirect to='/other/route' /> } for your redirects should work. Adding a separate field redirect: '/other/route' should work great as well.
all set, everything works, thanks again Tholle, really appreciate it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.