Twhitt06
Twhitt06

Reputation: 25

React Router: Creating pages dynamically from the Wordpress REST API

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>
      );
    }
}

Upvotes: 0

Views: 1378

Answers (1)

Jo Peyper
Jo Peyper

Reputation: 390

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.

Upvotes: 2

Related Questions