[Solved] How to navigate on path by button click in react router v4?

I have this paths in react-router-dom:

  <Route exact path='/(index.html)?' component={Home}/> {/* app = home */}
  <Route  path='/register' component={Registration}/>

everything is working fine, now anywhere in my components I want to change path by onClick, a code like this:

<button onClick={() => history.push('/the/path') }> change path </button>

how can I do that?

Solution #1:

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

class App extends React.Component {

  nextPath(path) {

  render() {
    return (
      <button onClick={() => this.nextPath('/the/path') }>
        change path 

export default withRouter(App);
Respondent: soywod

Solution #2:

If you’re using the button only for navigation, you can replace it with <Link />1 and apply a button style.

<Link to='/new/location/'>Click Me</Link>

Or you can use the <NavLink />2.

In case of using Material UI, you can use the following code:

import { Link } from 'react-router-dom'
import Button from '@material-ui/core/Button';

<Button component={Link} to="/new/location/">
  Click Me

(1): import {Link} from "react-router-dom";
(2): import {NavLink} from "react-router-dom";

Respondent: frogatto

Solution #3:

react-router-dom exports a hook called useHistory.
Just import it and use it in your component like this:

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

export default () => {
  const history = useHistory();
  return (
    <button onClick={() => history.push('/your/path')}>
      Click me

I’m using:

  • “react”: “^16.13.1”
  • “react-router-dom”: “^5.2.0”

Check this post for more details: https://ultimatecourses.com/blog/programmatically-navigate-react-router

Respondent: Bruno Ribeiro

Solution #4:

Nothing fancy but it gets the job done

 `<a href="http://localhost:3001/contact">  
      {" "}
      Contact Us{" "}
Respondent: Noah Franco

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.