How to use history in React.js?

by ryan.murray , in category: Javascript , 8 months ago

How to use history in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , a month ago

@ryan.murray 

In React.js, history is commonly used for navigation and changing the URL within a single-page application. The history object is usually provided by the React Router library.


To use history in a React component, you can access it using the useHistory hook provided by React Router. Here's an example of how you can use history to navigate to a different route:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import React from 'react';
import { useHistory } from 'react-router-dom';

const MyComponent = () => {
  const history = useHistory();

  const handleClick = () => {
    // navigate to a different route
    history.push('/new-route');
  };

  return (
    <button onClick={handleClick}>Go to new route</button>
  );
};

export default MyComponent;


In the example above, we first import the useHistory hook from 'react-router-dom'. We then access the history object by calling useHistory(). Inside the component, we define a function handleClick that uses history.push('/new-route') to navigate to the '/new-route' URL when the button is clicked.


This is just a basic example of how you can use history in a React component. There are many other features and methods provided by the history object that you can explore to build more complex navigation functionality in your React application.