How to create dynamic routes with react-router-dom?

  • Use Link to dynamically generate a list of routes.
  • Use : to indicate url params, :id in the case
  • Use the match object passed as props to the rendered route component to access the url params. this.props.match.params.id
<BrowserRouter>
  /* Links */
  {heroes.map(hero => (<Link to={'heroes/' + hero.id} />)}

  /* Component */
  <Route path="heroes/:id" component={Hero} />
</BrowserRouter>

class Hero extends Component {
  render() {
    return (
      <div>
        {this.props.match.params.id}
      </div>
    );
  }
}

Leave a Comment