I am trying the pass data to a new page by using Link, in doing so I used the following code.
<Link
className="option"
to={{
pathname: this.state.pathname,
state: id
}}
>
<span className="color-primary"> <button style={{ color: "white" }}
className="transaction-button"><i className="material-icons" style={{ fontSize: "18px" }}>sync_alt</i> Transaction</button>
</span>
</Link>
In the page routed, I tried to handle the data by the following code.
console.log(this.props)
The output is an empty object.
{}
Both pages are class component
I assume you are using
react-router.In the first page, where you use
<Link>...</Link>you're doing the right thing.At this point there are two alternatives: you can use function or class to create the component.
IF YOU USE A FUNCTION
In the second page, to take the data you passed, you have to import
useLocation:And then, inside the function, you have to call it and extract the state from it:
Inside
location.stateyou have the state you passed from the previous page.IF YOU USE A CLASS
In this case, things are little more complicated, but you can use
withRouterin order to injectlocationinside your component props.So, first of all you need to import
PropsTypesandwithRouter:Then you have to write your class like this:
In this way inside
location.stateyou have the state you passed from the previous page.