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

gpbaculio picture gpbaculio · Jul 3, 2017 · Viewed 53.7k times · Source

I have this paths in react-router-dom:

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

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?

Answer

soywod picture soywod · Jul 3, 2017
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);