DEV Community

Dhiman_aman
Dhiman_aman

Posted on

How to Create a Dynamic Routing using the Params() in ReactJS?

Use React Router Dom @6 Version to Route the Pages

Create One Page as Coin and use page in APP.js

import { Routes, Route } from "react-router-dom";
import "./App.css";
import Home from "../src/Page/Home";
import User from "./Component/User";
import About from "./Page/About";
import Navbar from "./Component/Navbar";
import Coin from "../src/Page/Coin";

function App() {
  return (
    <>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} exact />
        <Route path="/coin/:d" element={<Coin />}  />
        <Route path="/about" element={<About />}  />
        <Route path="/user/:id" element={<User />} />
      </Routes>
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

In the Coin Page

import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import Loading from "../Component/Loading";

const Coin = () => {
  const paramsData = useParams();
  const { d } = paramsData;
  const [u, sUser] = useState([]);
  const [check, setCheck] = useState(true);
  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/users/${d}`)
      .then((res) => res.json())
      .then((data) => {
        sUser(data);
        //console.log(data);
        setCheck(false);
      });
  }, []);
  return (
    <>
      <center>
        {check ? (
          <Loading />
        ) : (
          <>
            <p>
              <b>Name:</b> {u.name}
            </p>
            <p>
              <b>User Name:</b> {u.username}
            </p>
            <p>
              <b>Email: </b>
              {u.email}
            </p>
            <p>
              <b>Website:</b> {u.website}
            </p>
            <Link to="/">Go the Home</Link>
          </>
        )}
      </center>
    </>
  );
};

export default Coin;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)