Skip to content
Related Articles

Related Articles

How to navigate on path by button click in react router ?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 01 Feb, 2022

In this article, we will see how to navigate to another route via button component  in react.js.

Approach: To navigate to another page by clicking a button we will be using the useHistory hook. 

UseHistory hook: This method lets you access React Router’s history instance. This allows you to redirect users to a different page via the history instance.

A history object consists of the following properties and methods:

  • Length: The number of entries in a history stack
  • Action: Current action (PUSH, REPLACE, etc.).  Push(path, [state]) – Adds a new entry to the history stack.
  • Location: The current location.

To understand better, we will create a computer science portal application with a homepage and another page that gives an insight into the courses offered. By clicking the button on the homepage, you can explore the courses, present on the other route, and return to the homepage.

Below is the step-by-step implementation.

Step 1: Make a project directory, head over to the terminal, and create a react app named “ cs portal ”  using the following command.

npx create-react-app cs-portal 

After the cs portal app is created, you will see the following success message in the terminal and you are good to go. Switch to the new folder ‘cs portal ‘ by typing the command below:

cd cs-portal 

Step 2: Modify Your project structure. The Directory structure currently looks like this 

Default Directory Structure

We will modify the folder and keep the files we need for this example. Now, make sure your file structure looks like this 

DIRECTORY STRUCTURE

This is how the final project structure would look: 

Final Project  structure 

Step 3: Include the following code in your index.html file, located in the public folder of your project directory. We will use bootstrap to build our components.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1" />
    <meta name="theme-color" 
          content="#000000" />
    <meta name="description" 
          content="Web site created using create-react-app">
    <link rel="stylesheet" 
          href=
          integrity=
"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
          crossorigin="anonymous">
    <title>React App</title>
</head>
  
<body>
    <div id="root"></div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src=
            integrity=
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" 
            crossorigin="anonymous">
    </script>
    <script src=
            integrity=
"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" 
            crossorigin="anonymous">
    </script>
    <script src=
            integrity=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" 
            crossorigin="anonymous">
        </script>
</body>
  
</html>

Step 4: Add a new folder called components to the src folder. We will add components to this folder. In the components folder, create a new file Navbar.js, where we will put the code for our navbar. You can choose any logo of your choice and customize the navbar. I have used the geeksforgeeks logo in the navbar.  

Write this code in your Navbar.js file :

Navbar.js




import React from "react";
  
function Navbar() {
    return (
        <div>
            <nav className="navbar navbar-light bg-light">
                <img
                    src=
                    width="300"
                    height="75"
                    className="d-inline-block align-top logo"
                    alt=""
                />
            </nav>
        </div>
    );
}
  
export default Navbar;

Step 5: In this step, we will create the Homepage component. Create a new file called Homepage.js and write the following code. Our Homepage is built using the Bootstrap Jumbotron element. It refers to a big box for highlighting special content or information. You’ll see some information regarding the CS portal, for instance, geeksforgeeks. Furthermore, at the end of the box, there is a button that will take you to another route.  To use the useHistory hook in our project, we first need to install react-router-dom using npm. 

npm i react-router-dom 

Installing react-router-dom 

Then we will import the useHistory hook into our Homepage component 

import { useHistory } from "react-router-dom";

To navigate to the courses route, we will use the history.push method of the useHistory object.  We will add an event handler “onClick” for our button component and define a function “coursesPage ” that handles the click event. The coursesPage function enables us to redirect to another route on clicking the button. 

Homepage.js




import React from 'react'
import { useHistory } from "react-router-dom";
import "../App.css";
  
function Homepage() {
    const history = useHistory();
  
    const coursesPage = () => {
        history.push("/courses")
    }
    return (
        <>
  
            <div className="jumbotron text-center">
                <h1 className="display-4">Hello,Geeks</h1>
                <p className="lead">
                    Geeks for Geeks is a Computer Science portal.  
                    It contains well written, well thought and well 
                    explained computer science and programming articles
                </p>
  
                <hr className="my-4" />
                <p>
                    Real-time Live and self paced courses carefully
                    curated for you !
                </p>
  
                <p className="lead">
                    <button className="btn btn-success"
                        onClick={coursesPage}>Explore Courses
                    </button>
                </p>
  
            </div>
        </>
    )
}
  
export default Homepage

Step 6: Now ,we will create our Courses component. It consists of a card where all the courses are listed and a button that returns you to the homepage. Create a new file Courses.js and write the following code in it. 

Javascript




import React from 'react'
import "../App.css";
import { useHistory } from "react-router-dom";
  
function Courses() {
    const history = useHistory();
    const home = () => {
        history.push("/");
    }
    return (
        <>
            <div className="card " >
                <h1>Courses </h1>
                <ul className="list-group list-group-flush">
                    <li className="list-group-item">
                        Data Structures & Algorithms
                    </li>
                    <li className="list-group-item">
                        Competitive Programming
                    </li>
                    <li className="list-group-item">
                        Full Stack Development
                    </li>
                    <li className="list-group-item">
                        Java Backend
                    </li>
                </ul>
            </div>
            <button className="btn btn-success" onClick={home}>
                Back to Home
            </button>
        </>
    )
}
  
export default Courses

Step 7: Now, let’s style our components. Write the following code in the App.css file.

App.css




* {
    text-align: center;
}
  
.logo {
    margin: auto
}
  
.jumbotron {
    margin: 100px auto;
    max-width: 50%;
    text-align: center;
}
  
.card {
    width: 18rem;
    margin: 100px auto;
}

Step 8: Remove the existing code from your App.js file and replace it with the following code to render the components. We will use the react-router dom for the basic routing. Both the homepage and the courses pages will have a navbar component. We will have separate routes for the homepage and courses by using the switch, route methods available in V5 react-router. This will render the component that matches the exact path.  

App.js




import React from 'react';
import {
    BrowserRouter as Router,
    Switch,
    Route,
    Link
} from "react-router-dom";
import Homepage from "./Components/Homepage"
import Courses from "./Components/Courses"
  
import './App.css';
import Navbar from './Components/Navbar';
  
function App() {
    return (
        <>
            <Navbar />
            <Router>
                <Switch>
                    <Route exact path="/" 
                        component={Homepage} />
  
                    <Route exact path="/courses" 
                        component={Courses} />
                </Switch>
            </Router>
        </>
    );
}
  
export default App;

Step 9: Your index.js file should look like this. The index.js file serves as the main entry point, and inside it the App.js file is rendered at the root ID of the DOM.

index.js




import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
  
ReactDOM.render(
    <App />, document.getElementById('root')
);

Step to run the application: Now let us run our application by using the following command. 

npm start 

Output: By default, the React project will run on port 3000. You can access it at localhost:3000 on your browser. 

Working code output 

You can watch the geeksforgeeks video to learn more about react.js routing. 

&list=PLqM7alHXFySGUg_8Ac5yqZy2_1V-V1Py5&index=10
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!