How can i pass Data from Main Component to child component based on the record Id. I have a index.js
and detail.js
pages. In the index page i have a link as <Link to={{ pathname:
/cards/ ${results.id} , state: results }} className={
card-wrapper restore-${results.id} }> {results.first_name} </Link>
when i click on the link i want to send the data associated to that record /Id value of the link to the detail page and display.
Ok, I've examined your code and you need to do 2 changes: From your index.js file, you need to change your link's to prop to:
to={{ pathname: `/cards/${results.id}`, state: results }}
In your details.js, change your render function to:
render() { const id = this.props.match.params.id; const data = cardData.data.Table.find(item => item.id === id) return ( // Card details compoment <div className="card-details"> <h2>{data.first_name}</h2> <h2>{data.id}</h2> <Link to={{ pathname: "/", state: this.props.location.state }} > <button>Return to list</button> </Link> </div> ); }
Notice in the Link that you are linking to /cards/${results.id}
, the id is the id of the record from the database.
Then in details.js,you find from the data a record with the id from the params and you use the data in that record.
You had done 2 mistakes:
/cards/${results.index}
in index.js, results.index
is undefined. cardData.data.Table[id].first_name
But cardData.data.Table
is an array of Objects and the ids are properties of the objects. cardData.data.Table[id] would only return data for an id such as 1002 if that array had at least 1003 objects in it.
In this case, you can pass cardData.data.Table data to as props & get id from router like .....params.id.
Then replace cardData.data.Table[0] by cardData.data.Table[i].
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.