user7024499 user7024499 - 1 month ago 6
React JSX Question

React Router - Is there an 'easier' way to route to a new path besides using Context?

Is there an easier or perhaps more recent way to be able to, for instance, click on a button and onClick of that button, reroute to a new path?

....BESIDES using the context method on the component?

Thanks

Answer

There are ways:

1.withRouter - HoC from react-router (higher-order component) that wraps another component to provide props.router

import { withRouter } from 'react-router';

class App extends Component {
   ...
    onClickButton(){
      this.props.router.push('/path')
    }
   ...
}

export default withRouter(App);

2.History singleton (hashHistory / browserHistory)

import { hashHistory} from 'react-router';

class App extends Component {
   ...
    onClickButton(){
      hashHistory.push('/path')
    }
   ...
}

3.Also you can get history from props in component, wich is passed to route

....
<Route path="/" component={App} />

then in Component

class App extends Component {
   ...
    onClickButton(){
      this.props.history.push('/path')
    }
   ...
}
Comments