React button click navigate to new page

Dhruva
Aug 13, 2019

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.

Home page without button to products

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.

package.json file

Below is the code for index.js file which includes App and rendering of the components.

index.js file

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

Routes.js file

I created history.js file separately which can be used in multiple places.

History.js file

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.

Home.js file

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

Products.png

Find below is the github link for the project.

https://github.com/minioncoder/ReactButtonExample

--

--