My react app consists two main pages, the first page contains 4 main sections that displays together (Home – about – products – contact) and I navigate between them by smooth scrolling.
What I expect is when I click on the image of a specific product it needs to open the product specs page in a new page. But it opens it in the same page and the component is added below the contact section.
Here is the code :
import React from 'react'
import {BrowserRouter , Routes, Route} from "react-router-dom";
import Navbar from './components/Navbar'
import Home from './components/Home'
import About from './components/About'
import Machines from './components/Machines'
import Contact from './components/Contact'
import Product1 from './components/Product1'
function App() {
return (
<BrowserRouter>
<Navbar />
<Home />
<About />
<Machines />
<Contact />
<Routes>
<Route path="/product1" element={<Product1 />} />
</Routes>
</BrowserRouter>
);
}
export default App;
//Machines.js
<figure>
<Link to="/product1"><img src={image1} alt="Image 1" /></Link>
<figcaption>
<p>Manual Cocker Machine</p>
</figcaption>
</figure>
2
Answers
The navbar component should be rendered in each page, not here at the top level
You are unconditionally rendering all your main content, e.g.
Home
,About
, etc, and then below that conditionally rendering theProduct1
component via the router and its own route.If you only want the main content to be conditionally rendered when on a "home" page then you’ll want to conditionally render them on a route as well.
Here’s an example refactor to use a layout route to render the
Navbar
component and each page as a nested route under it. TheNavbar
will render above all routed content on each page, your main content will be rendered on the root"/"
path, and the product page will still be rendered on"/product1"
as before.