I am doing a project on an ecommerce site and currently have the correct routes set up for the home page at "/"
and for the product list page at "/:id"
. I am trying to get a route set up for a single product page however, react-router does not render my component at all.
Index.js
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>), document.getElementById('root'));
registerServiceWorker();
App.js
<Switch>
<Route exact path="/" render={()=> apiDataLoaded ? <HomeLayout data={data}/> : <div>Loading...</div>}/>
<Route path="/:id" render={(props)=> <ProductListLayout {...props} />} />
</Switch>
Listing Component
return (
<Switch>
<div className="product-list-item-card">
<div className="product-list-item-img" style={bgImage}></div>
<div className="product-list-item-content">
<div className="product-list-item-overlay">
<Link to={`/products/${id}`}>
<DetailsBtn />
</Link>
</div>
<h3>{name}</h3>
<h6>{brand}</h6>
<span>${msrp}</span>
<p>${sale}</p>
</div>
</div>
<Route path={'/products/:product_id'} render={()=> <div>Product Page</div>}/>
</Switch>
)}
In the listing component above, when I clock on the link, the url is the only thing that changes? Any ideas as to what I'm doing wrong? Thanks.
SOLVED
Changing the order of the routes in App.js was only part of the solution. I also moved my route from the Listing component into App.js at the top of the order of the routes and now it works!
New App.js
<Switch>
<Route path={`/products/:product_id`} component={ProductLayout} />
<Route path="/:id" render={(props)=> <ProductListLayout {...props} />} />
<Route exact path="/" render={()=> apiDataLoaded ? <HomeLayout data={data}/> : <div>Loading...</div>}/>
</Switch>
you need to change only position on your current routes...
<Switch>
<Route path="/:id" key={1} render={(props)=> <ProductListLayout
{...props} />} />
<Route exact path="/" key={1} render={()=> apiDataLoaded ?
<HomeLayout data= .
{data}/> : <div>Loading...</div>}/>
</Switch>
Remove switch and use div inside ProductListLayout component
ProductListLayout.js
const ProductListLayout = () => {
return (
<div>
<div className="product-list-item-card">
<div className="product-list-item-img"></div>
<div className="product-list-item-content">
<div className="product-list-item-overlay">
<Link to={`/products/${99999}`}>
Click here
</Link>
</div>
<h3>{name}</h3>
</div>
</div>
<Route exact path={`/products/:product_id`} render={()=> <div>Product Page</div>}/>
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.