How to Navigate using History Push in React Router
Table of Contents
One of the best parts about single-page applications is the fact that navigation does not trigger an entire page refresh in the browser.
When you use React, you can trigger navigation programmatically using the history
object.
In this post, we'll learn how you can navigate programmatically in React.
Navigating Programmatically in React
The most popular library to handle routing is react-router-dom
. This is the router that is written by the same team that wrote React.
This library will allow you to navigate programmatically in React by attaching the history
object as a property which allows you to call it from within your React component.
The history.push
function takes in the path you want to navigate to, and then and state that you want to pass along.
Let's look at an example of how to use this method in React:
JAVASCRIPTthis.props.history.push("/about", {
name: "John Doe"
});
Let's look at an example in a full React component:
JSXimport React from "react";
import { withRouter } from 'react-router-dom';
class ExampleComponent extends React.Component {
exampleFunction() {
this.props.history.push("/about");
}
}
const ExampleComponentWithRouter = withRouter(ExampleComponent);
This component contains a function that will navigate to the /about
route when called.
The wrapping of the component with withRouter
will allow you to access the history
object.
Conclusion
In this post, we saw how to use the history
object to navigate programmatically in React by using react-router-dom
.
Simply wrap your component with withRouter
and you can access the history
object to use the push
function.
Thanks for reading and hope this helps!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- How to build a Discord bot using TypeScript
- Getting User Location using JavaScript's Geolocation API
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up a Local Web Server using Node.js
- Getting Started with Moon.js