Reputation: 107
I've a object:
{
"products": [
{
"id": 1,
"category": "Milk & meat",
"products": {
"product1": ["Name", "Recipe", "Photo"]
}
}
}
and it's mapped like that:
return (
<div className="box list">
{this.props.products
.map((product, ind) =>
<div key={ind}>
<h2>{product.category}</h2>
{Object.values(product.products).map(name => <li onClick={this.props.handleClickedProduct}>{name[0]}</li>)}
</div>)}
</div>
)
The onClick method passes the product name ([0] in array) to other component. It does it like that:
handleClickedProduct = (e) => {
this.setState({ clickedProduct: e.target.innerHTML });
}
How cane I setState [1] and [2] from the same array? I want to pass forward the product name and keep in state the recipe and photo.
Thanks, Kuba
Upvotes: 0
Views: 1221
Reputation: 368
class Example extends React.Component {
products = [
{
id: 1,
category: "Milk & meat",
products: {
product1: ["Name", "Recipe", "Photo"]
}
},
{
id: 2,
category: "Milk & bread",
products: {
product1: ["Name", "Recipe", "Photo"]
}
}
]
state = {
clickedProduct: null
}
handleClick = (product) => (e) => {
this.props.onClick(product)
}
render() {
return (
<div className="box list">
{this.products.map((product, ind) =>
<div key={ind}>
<h2>{product.category}</h2>
<ul>
{Object.values(product.products)
.map(pr => <li onClick={this.handleClick(pr)}>{pr[0]}</li>)}
</ul>
</div>)
}
</div>
)
}
}
class Handler extends React.Component {
handler = (e) => {
console.log(e)
}
render () {
return <Example onClick={this.handler}/>
}
}
ReactDOM.render(
<Handler />,
document.getElementById('container')
);
Change handleClickedProduct
to be
handleClickedProduct = (name) => (e) => {
this.setState({ clickedProduct: e.target.innerHTML });}
and inside your map you can just do this.handleClickedProduct(product.products)
and use it inside the handleClickedProduct
function.
Upvotes: 1