John107
John107

Reputation: 2287

React component displaying dynamic data based on URL

I want to create a single dynamic component that displays data from a json file dependant on the url. Instead of manually creating and storing each page.

For example: https://jsonplaceholder.typicode.com/posts

on page route: /1 the page would display:

Title = unt aut facere repellat provident occaecati excepturi optio reprehenderit

Body = quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto.

How would I return specific data from the json? Here's a quick fiddle: https://jsfiddle.net/pb2tL7ma/

Any suggestions would be appreciated!

Upvotes: 0

Views: 1935

Answers (3)

Tholle
Tholle

Reputation: 112807

One way of going about it is to use React Router with URL parameters and create a Link for every page in your pages array, and use this URL parameter to extract the page you want to view.

Example (CodeSandbox)

class App extends React.Component {
  state = {
    pages: []
  };

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/posts`).then(res => {
      this.setState({ pages: res.data });
    });
  }

  render() {
    const { pages } = this.state;

    if (pages.length === 0) {
      return null;
    }
    return (
      <BrowserRouter>
        <div>
          <Route
            exact
            path="/"
            render={() => (
              <ul>
                {pages.map(page => (
                  <li>
                    <Link to={`/${page.id}`}>{page.title}</Link>
                  </li>
                ))}
              </ul>
            )}
          />
          <Route
            path="/:page"
            render={({ match }) => {
              const pageParam = Number(match.params.page);
              const page = pages.find(p => p.id === pageParam);

              return <div>{page.title}</div>;
            }}
          />
        </div>
      </BrowserRouter>
    );
  }
}

Upvotes: 1

Rafael Rocha
Rafael Rocha

Reputation: 518

As mentioned above you can use react-router-dom for that or basically just use the Window.location object. It's already available out of the box so you don't need an external dependency.

Upvotes: 0

Ertan Hasani
Ertan Hasani

Reputation: 1773

Try using react-router-dom. Add a route in App.js like this:

<Route path='/posts/:id' component={DynamicData} />

And then you can get that id in your DynamicData component by:

this.props.match.params.id

Upvotes: 0

Related Questions