0

I've created an array of elements that I've retrieved from the Wordpress REST API JSON object. I want to use react-router to make each element its own separate page using its id as the slug e.g. (/items/1).

I've hit a bit of a wall and haven't able to figure out how to dynamically create the routes using react-router. Any guidance would be much appreciated!!!

export default class ItemContainer extends React.Component {

  constructor(){
      super();
      this.state= {
        items: []
      }
    }

    componentDidMount(){
      var th = this;
      this.serverRequest =
      axios.get('http://website.com/wp-json/wp/v2/item/')
        .then(function(result) {
          th.setState({
          officers: result.data
        });
      })
    }

    componentWillUnmount(){
      this.serverRequest.abort();
    }


    render(){

      const ItemComponents = this.state.items.map((item) => {
        return <Item key={item.id} {...item} />;
      });


      return(
          <div className="item-wrapper">
            {ItemComponents}
          </div>
      );
    }
}

1 Answer 1

2

The approach you probably want to take is to not create specific routes for each item and use a param instead.

Your path could look something like this:

<Route path="/items/:itemId" component={ItemPage} />

This will allow you to get the itemId in the ItemPage component and load the correct content. If you get a id that does not correspond to a valid item, redirect to an error page or any other page you like.

You can access the itemId param on the props of ItemPage like:

this.props.params.itemId

If you really feel you must have specific routes for each item, you will need to get your hands dirty with Dynamic Routing.

Sign up to request clarification or add additional context in comments.

Comments

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.