Reputation: 88
I have recently started learning react and react-router-dom. My task is to route the pages dynamically and view data as per the dynamic routes.
so when i routed to this url http://localhost:3000/category it should display all the categories and when i click each of the category it should render only the child component with the data. Currently it is rendering with the parent component.
Example: if i route to this url http://localhost:3000/category/nike it should render only the Product component with nike description. Below is my code. Please help me with your suggestion.
App.js
import { Link, Route, Switch } from "react-router-dom";
import './App.css';
import Home from './Home';
import Category from './Category';
function App() {
return (
<div className="App">
<nav className="navbar navbar-light">
<ul className="nav navbar-nav">
<li>
<Link exact to="/">Home</Link>
</li>
<li>
<Link to="/category">Category</Link>
</li>
</ul>
</nav>
<Switch>
<Route exact path="/"><Home /></Route>
<Route path="/category"><Category /></Route>
</Switch>
</div>
);
}
export default App;
Category.js
import React from 'react'
import { Link, Route, useParams, useRouteMatch } from "react-router-dom";
import Product from './Product';
export default function Category() {
const { url, path } = useRouteMatch();
const productData = [
{
id: 1,
name: "nike",
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin molestie.",
status: "Available",
},
{
id: 2,
name: "slippers",
description:
"Mauris finibus, massa eu tempor volutpat, magna dolor euismod dolor.",
status: "Out of Stock",
},
{
id: 3,
name: "Adidas",
description:
"Maecenas condimentum porttitor auctor. Maecenas viverra fringilla felis, eu pretium.",
status: "Available",
},
{
id: 4,
name: "puma",
description:
"Ut hendrerit venenatis lacus, vel lacinia ipsum fermentum vel. Cras.",
status: "Out of Stock",
},
];
return (
<div>
<ul>
{productData.map((product) => {
return (
<li>
<Link to={`${url}/${product.name}`}>{product.name}</Link>
</li>
);
})}
</ul>
<Route path={`${path}/:name`}>
<Product />
</Route>
</div>
)
}
Product.js
import React from 'react'
import { useParams } from 'react-router-dom';
export default function Product() {
const {name} = useParams();
return (
<div>
{name}
</div>
);
}
Upvotes: 0
Views: 578
Reputation: 2194
The way you have written code in write but that's not the best way to do it , Common and easy way is to create a component for All category view and Particular Category view , another way is to use route /category
with one component but use query like this /category?name=nike
, then you can get the query field name value and match , if that field is missing then we can display all the categories
I have written in code sandbox to explain the same , you can refer to that architecture and implement the same
Upvotes: 1