Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

reactjs

I learn react and know, how to create static routes, but can't figure out with dynamic ones. Maybe someone can explain, I'll be very grateful. Let there be two components, one for rendering routes, and another as a template of a route. Maybe something wrong in the code, but hope You understand..

Here is the component to render routes:

import React, { Component } from 'react';
import axios from 'axios';
import Hero from './Hero';

class Heroes extends Component {
  constructor(props) {
    super(props);
    this.state = {
      heroes: [],
      loading: true,
      error: false,
    };
  }
  componentDidMount() {
    axios.get('http://localhost:5555/heroes')
      .then(res => {
        const heroes = res.data;
        this.setState({ heroes, loading: false });
      })
      .catch(err => { // log request error and prevent access to undefined state
        this.setState({ loading: false, error: true });
        console.error(err);
      })
  }
  render() {
    if (this.state.loading) {
      return (
        <div>
          <p> Loading... </p>
        </div>
      )
    }
    if (this.state.error || !this.state.heroes) {
      return (
        <div>
          <p> An error occured </p>
        </div>
      )
    }
    return (
      <div> 
        <BrowserRouter>
          //what should be here?
        </BrowserRouter>      
      </div>
    );
  }
}

export default Heroes;

The requested JSON looks like this:

const heroes = [
  {
    "id": 0,
    "name": "John Smith",
    "speciality": "Wizard"
  },
  {
    "id": 1,
    "name": "Crag Hack",
    "speciality": "Viking"
  },
  {
    "id": 2,
    "name": "Silvio",
    "speciality": "Warrior"
  }
];

The route component (maybe there should be props, but how to do it in the right way):

import React, { Component } from 'react';

class Hero extends Component {
  render() {
    return (
      <div>
        //what should be here?
      </div>
    );
  }
}

export default Hero;

I need something like this in browser, and every route url should be differentiaie by it's id (heroes/1, heroes/2 ...):

John Smith Crag Hack Silvio

Each of them:

John Smith. Wizard.

and so on...

Many thanks for any help!)

like image 582
Kiten Avatar asked Jul 16 '19 13:07

Kiten


People also ask

How can get dynamic ID from URL in react JS?

Use the useParams() hook to get the ID from a URL in React, e.g. const params = useParams() . The useParams hook returns an object of key-value pairs of the dynamic params from the current URL that were matched by the Route path. Copied!

Which router hook will you use to get dynamic parameters from a URL?

The useParams Hook In addition, since the match object is passed from Route into the rendered component, you'll need to pass the dynamic routes along to components further down the DOM tree.


1 Answers

  • 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>
    );
  }
}
like image 183
Avin Kavish Avatar answered Sep 26 '22 07:09

Avin Kavish