How to Navigate on Path by Button Click in React Router ?
Last Updated :
09 Jan, 2025
Navigation in React JS is done by implementing the routing between components using react-router-dom. To set navigation for components or events like button click, we can use the useHistory Hook provided in the react-router-dom v5.
Prerequisites:
Approach
Navigation in single-page applications is crucial for user experience. To navigate on the path by clicking a button we use the useHistory hook from react-router-dom v5 (i.e. useNavigate in v6). We will set the routes for specific components and navigate between them using a button.
Note: In react-router-dom v6 useHistory is replaced by useNavigate hook.
Steps to Create React Application and Install Modules
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
Step 2: Move to the project directory.
cd cs-portal
Project Structure:
Final Project structure The updated dependencies in package.json file.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^4.6.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^5.3.4",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: This example uses useHistory hook to navigate when the button is clicked.
CSS
/* Filename: App.css */
* {
text-align: center;
}
.logo {
margin: auto;
}
.jumbotron {
margin: 100px auto;
max-width: 50%;
text-align: center;
}
.card {
width: 18rem;
margin: 100px auto;
}
JavaScript
// Filename - 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 "bootstrap/dist/css/bootstrap.min.css";
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;
JavaScript
// Filename - Components/Navbar
import React from "react";
function Navbar() {
return (
<div>
<nav className="navbar navbar-light bg-light">
<img
src=
"https://media.geeksforgeeks.org/wp-content/uploads/20220125183244/g.png"
width="300"
height="75"
className="d-inline-block align-top logo"
alt="GfG.png"
/>
GeeksforGeeks
</nav>
</div>
);
}
export default Navbar;
JavaScript
// Filename - Components/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
JavaScript
// Filename - Components/Courses
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 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.
You can watch the GeeksforGeeks video to learn more about React JS routing.
Conclusion
To navigate on path using components and events we can define the routes first and implement the navigation using useHistory and useNavigate depending on the verson or react router used.
Similar Reads
How does React Router handle navigation in a React application?
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. Let us create a simple application to React to understand how the React Router works Re
3 min read
How to navigate to a parent route from a child route?
In angular, a root component that serves as the parent component of all the components and the rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component that is the parent of a child lies above the child component and
4 min read
Navigate Component in React Router
In React applications, navigation between different pages or views is an essential part of creating dynamic user interfaces. React Router is a popular library used for handling routing and navigation. One of the key features of React Router is the Navigate component, which allows for programmatic re
7 min read
How to Create Button in React-Native App ?
React Native provides pre-defined components like button and TouchableOpacity to create buttons in a react native app. In this article, we will see how to create buttons in react-native, their syntax, and different types of buttons available in react-native.Table of ContentApproachButton in React Na
4 min read
How to programmatically navigate using React Router ?
React Router provides a way to navigate between different parts of an application when certain events occur, such as button clicks or form submissions. Programmatically navigating allows us to change the URL of an application without a full page reload, enabling a smoother user experience. We will d
3 min read
How to handle Nested Routes in React Router ?
React Router allows us to create a hierarchical structure where child components can be rendered within parent components, resulting in a seamless navigation flow. In this article, we will see how to handle nested Routes in React Router. Approach to handle Nested RoutesTo implement nested routes in
3 min read
How To Enable Button Based On If statement in ReactJS?
React.js is one of the most popular JavaScript libraries for building user interfaces, and one common task is enabling or disabling a button based on certain conditions or user inputs. This is often achieved by using conditional logic such as if statements.In this article, we'll explore how to enabl
2 min read
How to add navigation links to the React Bootstrap Navbar?
In ReactJS, we use Nabvar or Navigation Bar as the core component. For ease of navigation over the application, we use this NavBar in react-bootstrap. We need to add navigation links to go through different routes or pages of the application. So to add the navigation links to the React Bootstrap Nav
5 min read
How to Display a Simple Loading Indicator Between Routes in React Router ?
Displaying a loading indicator between routes helps in transitioning between routes that involve loading data or components asynchronously. During this transition period, it's essential to provide visual feedback to users to indicate that something is happening. It is a good practice to display a lo
3 min read
Mastering React Routing: Learn Navigation and Routing in React Apps
React Routing is a technique used to handle navigation within a React application. It enables users to move between different views, pages, or components without refreshing the entire page, which is a key feature of Single Page Applications (SPAs).In this article, we will explore the essential conce
6 min read