How do I navigate the path with a button click in response to v4 router?

I have these paths in react-router-dom:

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

      

everything works fine, now somewhere in my components I want to change the path by onClick, code like this:

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

      

How can i do this?

+6


source to share


2 answers


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

class App extends React.Component {
  ...

  nextPath(path) {
    this.props.history.push(path);
  }

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

export default withRouter(App);

      



+9


source


If you are using a button for navigation only, you can replace it with <Link/>

1 and apply the button style.

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

      

Or you can use <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
</Button>

      


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


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

0


source







All Articles