How to Give Dynamic Routing in react js using simple array of object file

Tags: , , , ,



const userdata = [
{
    id:1,
    name:"kuber",
    phone:"8989"
},
{
    id:2,
    name:"sahil",
    phone:"9696"
}

];
export default userdata

From this to>>> <Route path={"user/:id"} component={user} />

What code should i use in “User” component if useParams has id=1 then how to show only id 1, name kuber, phone 8989

Answer

In the simplest way you can do it like this:

in your User.js/jsx import the userData. Then you can get the id from url using props.match.params.id and then you can filter from userData from that props.match.params.id . Note: You need to do this inside so every time id changes it gets the user of that id

useEffect(()=>{

 // your code here
 
},[props.match]);


Source: stackoverflow