I am working on a project where I have to pass data from one page to another.
For example, I have data on the first page.
let data = [
{id:1, name:'Ford', color:'Red'},
{id:2, name:'Hyundai', color:'Blue'}
]
Here is the first component page where I render this list of data with the name.
class ListDetail extends Component {
constructor();
handleClick(data){
console.log(data);
}
render() {
return (
<div>
<Hello name={this.state.name} />
<ul>
{data.map((data,i) => {
return <li onClick={this.handleClick.bind(this,data)}>{data.name}</li>
})}
</ul>
</div>
);
}
}
I want to pass this data to the next page where I need this data and more data than this. I am using React Router 4. Any suggestion or help would be helpful.
Advertisement
Answer
You can use the Link component from react-router and specify to={} as an object where you specify pathname as the route to go to. Then add a variable e.g. data to hold the value you want to pass on. See the example below.
Using the <Link /> component:
<Link
to={{
pathname: "/page",
state: data // your data array of objects
}}
>
Using history.push()
this.props.history.push({
pathname: '/page',
state: data // your data array of objects
})
Using either of the above options you can now access data on the location object as per the below in your page component.
render() {
const { state } = this.props.location
return (
// render logic here
)
}
You can see an example of how to pass a value along with a route in another example here.