Get Data with React’s Dynamic Routes

The most of us have heard about routing. However, the underlying methods used by SPA frameworks and routing libraries differ. Routing methods that are static and dynamic are two examples. Static routing was formerly supported by frameworks like Angular, Ember, and React Router library.

React Router is a library that allows for dynamic routing by conditionally rendering components depending on the route being used in the URL, and also by fetching api calls based on route parameters.

Dynamic routing, however, was just introduced by React Router to solve some of the main drawbacks of static routing.

<Route path="/project/:id">
  <SingleProject />
</Route>

The id argument may be used to locate the post data in our data source before generating the component, making match also available in inline generated routes.

The id argument may be used to locate the post data in our data source before generating the component, making match also available in inline generated routes.

Example:

const posts = [
  { id: 1, title: 'First', content: 'Hello world!' },
  { id: 2, title: 'Second', content: 'Hello again!' }
]

const Post = ({post}) => (
  <div>
    <h2>{post.title}</h2>
    {post.content}
  </div>
)

//...

<Route exact path="/post/:id" render={({match}) => (
  <Post post={posts.find(p => p.id === match.params.id)} />
)} />


Example: 

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

import Home from "./pages/Home";
import Post from "./pages/Post";

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/post/:id" component={Post} />
      </Switch>
    </Router>
  );
};

export default App;



We added a parameter named id to the post route that will be used to subsequently obtain the relevant post. Additionally, each of our pages must now be made.

export default App;

import React from "react";

const Home = () => {
  return <h1>Home</h1>
};

export default Home;



Let’s start by dealing with the component’s state; for this, we’ll utilise the useState() hook. Additionally, we already plan on having a list of posts, thus the state will be an array.

import React, { useState } from "react";

const Home = () => {
  const [posts, setPosts] = useState([]);
  return <h1>Home</h1>
};

export default Home;


As soon as the component is rendered, we must fetch the data; to do this, we will utilise useEffect() and axios to use the jsonplaceholder API.

import React, { useEffect, useState } from "react";
import axios from "axios";

const Home = () => {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    const fetch = async () => {
      try {
        const { data } = await axios.get("https://jsonplaceholder.typicode.com/posts");
        setPosts(data);
      } catch (err) {
        console.error(err);
      }
    };
    fetch();
  }, []);
  return <h1>Home</h1>
};

export default Home;




Leave a Comment

Your email address will not be published. Required fields are marked *

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top