0

In my react app I want to send state to the next path through the history.location.state and history.location.pathname

In my case, it has to push successfully and also showing in history but when I console.log(this.props.history) in the child page showing undefined.

MyComponent Code

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class MyComponent extends Component {
state = {
          cart: {
                    1:{
                       icon: "URL"
                       id: 1
                       quantity: 1
                       title: "item1"
                      }
                    2:{
                       icon: "URL"
                       id: 2
                       quantity: 1
                       title: "item2"
                      }
             }
        }

submitHandler = (event) => {
        event.preventDefault();
        let data = {};
        for (let key in this.state.cart) {
            data[key] = this.state.cart[key]
        }
        console.log("data=",data);
        this.props.history.push({
            pathname: "/result",
            state: { data: data }
        });

    }

render(){
return(
             <div >
               <button  onClick={this.submitHandler}>CONTINUE</button>
             </div>
         )
     }
}
export default withRouter(MyComponent);

Result Component

import React, { Component } from 'react';

class Result extends Component {
render() {

        console.log("ss=",this.props.history);

        return(<div>Result</div>)
}

export default Result;

In Console

enter image description here

Route

<Route path="/result" component={Result} />

As shown in the above img in history->location->state is push fine. But when I console log to this.props showing undefined.

Also I already use withRouter hoc of react-router-dom in export

Suggest me a solution to this?

1 Answers1

-1

May be you are called wrong path. its working and the state variable available on this.props.location not a this.props.history;

Codesanbox example

prasanth
  • 22,145
  • 4
  • 29
  • 53
  • please post you route initiated component. May be you [have this problem](https://stackoverflow.com/questions/65810103/i-am-passing-the-props-to-a-functional-component-via-link-react-router-dom-but/65810234?noredirect=1#comment116359325_65810234) – prasanth Jan 21 '21 at 12:43
  • @yuvraj https://codesandbox.io/s/zealous-cherry-mtlwp check this – prasanth Jan 22 '21 at 07:00