Here I will be using ‘history’ from react to navigate to a new page on button click.
I first created my react app using create-react-app and added Navbar component header which contains Home, About, Contact and Product pages.
Currently, the pages look like the below screen shot.
For your reference I added my package.json file here, I added all the recent versions of react, react-router-dom, react-bootstrap when this post is written.
Below is the code for index.js file which includes App and rendering of the components.
I have also added Routes.js file here that contains all the routes defined for the pages.
Note: Use import {Router} from react-router-dom instead of {BrowserRouter as Router} inside Routes.js file
I created history.js file separately which can be used in multiple places.
On Home page I added a Button component from react-bootstrap, onClick it navigates to products page using ‘history.push’ method
Below is the code for adding a button and history on the home page.
Now, on button click from home.js file we will get the products page when button is clicked. Below is the screenshot for above navigation.
After we click on the button the products page looks like below
Find below is the github link for the project.