Hello, Today we are looking at how in React button clicks navigate to another page. Here I using ‘History’ from react to a new page on button click. Firstly, I created a React Project and added Header, Home, Products components. Below You can see the home page of my react project. Here I am going to do this when I click on the “view products” button, It will navigate to the Products page. Lets’s see How can we do it.
Here we have to install react-router-dom.
npm install react-router-dom
After that, we can look at the index.js file. Below you can see my index.js file which contains App and rendering of the components
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import './index.css';
import Routes from './Routes';
import Header from './components/header/Header';
ReactDOM.render(
<Router>
<div className="App">
<Header/>
<Routes />
</div>
</Router>,
document.getElementById('root')
);
To define All routes I created the Router.js file and you can see it below.
import React, { Component } from "react";
import { Router, Switch, Route } from "react-router-dom";
import Home from "./components/home/Home";
import Products from './components/products/Products';
import history from './history';
export default class Routes extends Component {
render() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/Home" exact component={Home} />
<Route path="/Products" component={Products} />
</Switch>
</Router>
)
}
}
Here I created History.js file separately. Because we can use it anywhere we want.
import { createBrowserHistory as history} from 'history';
export default history();
Next on my Home component, I added onClick to the button using “history.push” method. When the button clicks it will navigate to the product component. Below you can see code of the my Home.js
import React from 'react';
import history from '../../history';
import './Home.css';
function Home(){
return(
<div className="Home-main">
<h1>This is Home Page</h1>
<button onClick={()=> history.push('/Products')} className="Home-button">View Products</button>
</div>
);
}
export default Home;
Now you can get output like below.
You can see this project through my Github View Here. Now I think you got a clear idea about how to navigate from one page to another page using the button onClick. Please stay tuned with Maztars to know more. Thanks a lot and see you at the next lesson. If you have any problem with this lesson comment on it. Let’s meet in the next lesson. And you can follow our React Tutorial HERE.