1

I am trying to dynamically create routes using react-router-dom. The route will depend on the id of a state I have in one of my components. How can I achieve this? App.js:

function App() {
  return (
    <div className="App">
      <Router>
        <Route path="/" component={Categories}></Route>
        <Route path="/:cat" component={Recipes}></Route>
      </Router>
    </div>
  );
}

Categories.js which I want to get the id (:cat) from - the state categories has an id value:

class Categories extends React.Component {
    state = {
        categories: []
    }

    componentDidMount() {
        fetch('http://localhost:8000/api/categories/')
            .then(response => response.json())
            .then(data => {
                this.setState({categories: data});
            });
    }

    render() {
        return (
            
        );
    }
}

I have seen others use useParams but I can't do that since Categories is a class. Thank you for the help.

3
  • A <Route path="/:cat" component={Recipes} /> is all you need to create a dynamic route. Are you really trying to ask a different question, like how to then navigate to a dynamic route? You're correct, the useParams hook can't be used in a class component, but it also isn't used to generate routes, it gives you the currently matched route's match.params. Please clarify what you are trying to do and what, if any, issue is. Commented Sep 14, 2021 at 1:00
  • So the 'categories' state has an 'id' property to it. What I want to do is create multiple routes using the ids from categories. Ex/ categories = [id=4]. I want the route to be "/4". If categories=[id=8], the route should be "/8". Commented Sep 14, 2021 at 1:29
  • path="/:cat" handles that. The ":cat" is a "placeholder" for the actual value of the path, i.e. if you navigate to "/4" then in the route match.params.cat will be "4". Does this make sense? Also, categories = [id=4] isn't valid array syntax. Commented Sep 14, 2021 at 1:34

1 Answer 1

1

Use

this.props.match.params

i.e:

import { BrowserRouter, Route, Router, Switch } from "react-router-dom";
import React from "react";

function App() {
  return (
    <div className="App">
      <p>R</p>
      <BrowserRouter>
       <Switch>
        <Route path="/categories/:id" component={Recipes}></Route>
        <Route path="/" component={Categories}></Route>
       </Switch>
      </BrowserRouter>
    </div>
  );
}

class Categories extends React.Component {
  state = {
    categories: []
  };

  componentDidMount() {
    fetch('http://localhost:8000/api/categories/')
        .then(response => response.json())
        .then(data => {
            this.setState({categories: data});
        });
}
  render() {
    return (
      <div>
        {this.state.categories.map((c) => (
          <div>CAT: {c.name}</div>
        ))}
      </div>
    );
  }
}

class Recipes extends React.Component {
  state = {};

  componentDidMount() {
     console.log('Params:',this.props.match.params)
  }

  render() {
    return <div></div>;
  }
}
export default App;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it makes more sense now.

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.