Introduction

In this article we will learn about React-router, and what is router. Programmatic navigation in React Router refers to the process of dynamically navigating to different routes in a React application using JavaScript code, rather than using standard navigation controls like links. ...but what does that really mean? As we all know, React is the most popular programming language in the market. Okay, let's move on.

What is the Routing?

React Router, a popular routing library for React, provides the following key features

React Programmatic Routing

React Router provides the following methods to programmatically navigate:

  1. useHistory() hook
  2. withRouter() HOC
  3. context.router.history.push()
  4. The useHistory hook returns the history object from the React Router, which has a push method that can be used to navigate to a different route.

1. useHistory() hook

The useHistory hook is a widely used feature offered by React Router, allowing access to the history object utilized by the library. This object provides methods to programmatically navigate through routes in the React application.

import { useHistory } from 'react-router-dom';
const history = useHistory();
history.push('/new-route');

2. withRouter() HOC

The withRouter Higher Order Component (HOC) gives access to the history object and can be used to programmatically navigate.

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  handleNavigation = () => {
    this.props.history.push('/new-route');
  };
  render() {
    return <button onClick={this.handleNavigation}>Go to new route</button>;
  }
}
export default withRouter(MyComponent);

3.context.router.history.push()

The context.router.history.push() method can be used with the context object to programmatically navigate.

import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
    static contextTypes = {
        router: PropTypes.object.isRequired
    };
    handleNavigation = () => {
        this.context.router.history.push('/new-route');
    };
    render() {
        return < button onClick = {
            this.handleNavigation
        } > Go to new route < /button>;
    }
}
export default withRouter(MyComponent);

Summary

In this article, you learned how to implement Rect Programmatic routings and routing key features also. Please use the comments section if you have any clarification.