Open In App

How to Navigate on Path by Button Click in React Router ?

Last Updated : 09 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 JavaScript JavaScript JavaScript

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.



Next Article

Similar Reads

three90RightbarBannerImg