How to pass data to another component via React Router on button click ?


I have an application, which changes routes (components) on a button click. How can I pass data to the component

rendered via React router when button is clicked ?

Answered question

There are 2 ways how this can be achieved.

  1. Pass the data to the component on route change via history.push() method as below.

Suppose on button click , if the below function is called.

function changeRoute(path) {
    // pass data like below
    this.props.history.push(path, {
      data: { <key>: <value> }
 Suppose this function is defined in the root App component, then this component should be declared as 
 class App extends React.Component {
 and exported as 
export default withRouter(App);
  Then in the child component, the data can be collected/received as:-
 componentWillMount(props) {

2. Second option is to use react-redux and connect to connect to a datastore and fetch the state from the store on an action dispatched on the button click which changes the route. In the child component, after the action fires and redux updates the parent state, the value can be retrieved via the state by using mapStateToProps or mapDispatchToProps whatever applicable.

Hope that helps !!

Changed status to publish
You are viewing 1 out of 1 answers, click here to view all answers.
Write your answer.