React Router: Navigate on Button click using useHistory hook

Last updated on April 16, 2021 Guest Contributor Loading... Post a comment

React Router (react-router-dom) is one of the most popular React libraries with over 42k stars on GitHub and nearly 4 million downloads per week on npmjs. In this article, you will learn how to programmatically navigate on a click event in React by using the useHistory hook provided by React Router.

Notes:

  • This tutorial uses functional React components and hooks so you you need React 16.8 or newer.
  • The useHistory hook only comes with React Router 5.1 and beyond. If you’re using React Router 5.0 or older, please upgrade it.

What is programmatic navigation?

Programmatic navigation means doing the navigation when calling a function instead of using <Link/> or <NavLink /> . For example, performing a navigation to a new route when the user clicks a button, checks a checkbox, selects an option from a select menu, enters the correct captcha code, completes valid information in a form. , etc.

The point of the useHistory hook

The useHistory hook gives you access to the history instance that you may use to navigate. It provides a few methods:

push('route-name')
replace('route-name')
location('URL')
goBack()
listen()

Simple usage:

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

const ExampleComponent = () => {
  const history = useHistory();
  const handleClick = () => history.push('/some-route');
  
  return (
    <button type="button" onClick={handleClick}>
      Navigate to another route
    </button>
  );
};

A Full Example

This simple example contains 2 routes: / (Home page) and /contact (Contact page). The user can go from the Home page to the Contact page by doing one of the following actions:

  • Click a button
  • Check a checkbox
  • Type “contact” into a text field

Preview:

The Steps

1. Create a new React:

npx create-react-app react_2021

2. Install react-router-dom:

npm i react-router-dom

Here’s my package.json:

{
  "name": "react_2021",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "antd": "^4.9.1",
    "axios": "^0.21.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

3. In the ./src folder, create 2 new files called Home.js and Contact.js then add the following code snippets, respectively:

import React from 'react';
import { useHistory } from 'react-router-dom';

const Home = (props) => {
  const history = useHistory();

  return (
    <>
      <h1>Home Page</h1>
      <p>Go to the contact page by using one of the following:</p>
      <hr />

      {/* Button */}
      <p>
        <button onClick={() => history.push('/contact')}>Go to Contact</button>
      </p>

      {/* Checkbox */}
      <p>
        <input
          type="checkbox"
          onChange={() => history.push('/contact')}
        ></input>
        <span>Check this checkbox to go to the contact page</span>
      </p>

      {/* Text field */}
      <p>
        <input
          type="text"
          onChange={(e) => {
            if (e.target.value === 'contact') {
              history.push('/contact');
            }
          }}
          placeholder="Enter 'contact' to navigate"
        ></input>
      </p>
    </>
  );
};

export default Home;
// Contact.js 
import React from 'react';
import { useHistory } from 'react-router-dom';

const Contact = (props) => {
  const history = useHistory();
  return (
    <>
      <h1>Contact Page</h1>
      <br />
      <button onClick={() => history.goBack()}>Go Back</button>
    </>
  );
};

export default Contact;

4. Remove all of the default code in App.js and add the following:

// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Home from './Home';
import Contact from './Contact';

const App = () => {
  return (
    <div style={styles.app}>
      <Router>
        <Switch>
          <Route path="/" exact>
            <Home />
          </Route>

          <Route path="/contact" exact>
            <Contact />
          </Route>
        </Switch>
      </Router>
    </div>
  );
};

export default App;

const styles = {
  app: {
    padding: 50
  }
}

Conclusion

Using the useHistory hook within your React applications gives us more strategies to navigate. If you’d like to learn more about React and React Native, take a look at our React category page and React Native category page for more tutorials and examples.

Related Articles

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x