Languages
[Edit]
EN

React / react-router - navigate to a route from event handler

0 points
Created by:
Dollie-Rutledge
776

In this short article, we would like to show you how to enter a direct path (e.g. from event handler) without using Link in React

1. Using useHistory

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

const App = () => {
  const history = useHistory();
  const clickHandler = () => {
    history.push('/path/to/your/page');
  };
  return (
    <button onClick={clickHandler} >Go to my path</button>
  );
};

export default App;

2. Using <Redirect>

import { Redirect } from 'react-router-dom'

const App = () => {
  const handleClick= () => {
    <Redirect to='/path/to/your/page'>;
  };
  return (
    <button onClick={handleClick} >Go to my path</button>
  );
};

export default App;

Note:

In <Redirect> the new location will replace the current location in the history stack, but history.push() will push the new entry on it.

References

  1. react-router docs

Alternative titles

  1. React - enter direct path without using Link
  2. React - useHistory
  3. React - programmatically change the route
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

React - react-router

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join