Im using React js for the front-end in a Laravel project. From a controller , im passing an array to my view:
return view('shopCart')->with('items',$it);
Now in the view a could loop through the array like this:
@foreach($items as $item)
<li><input type="checkbox" name=""> <span>{{$item->Name}}</span> <span></span> <span>{{$item->Cost}}</span> </li>
@endforeach
And this is working fine. But i would like to make the view more dynamic(by the way this is a list of products in a shopping cart). For example , by default all the checkboxes will be checked, meaning the user is buying all items. I want that if the user uncheck a box, the total price changes . So i made a React component , and im passing the $items array to that component via props:
<div id="listshops" datas={{$items}}></div>
And there's the component:
class Items extends Component {
render() {
return (
<div className="container">
<a href="/products">Continue shopping</a>
//LOOP THROUGH THE ARRAY OF PRODUCTS
</div>
);
}
}
export default Items;
window.onload=function(){
if (document.getElementById('listshops')) {
var data=document.getElementById('listshops').getAttribute("datas");
ReactDOM.render(<Items items={data}/>, document.getElementById('listshops'));
}
}
How can i loop through that array i passed to the component so i can display the product like in the @foreach in blade ?
Array#map, don't "loop". You're mapping one dataset (your products) into another dataset of equal size (React components)
const { items } = this.props;
return (
<div className="container">
<a href="/products">Continue shopping</a>
{items.map(({ Name, Cost }) => <li key={Name}>
<input type="checkbox" name="" /> <span>{Name}</span> <span></span> <span>{Cost}</span>
</li>)}
</div>
);
Often when you map, it's a good indication that you're using a component that could be reusable too. This could be a cleaner approach for you:
const Product = ({ Name, Cost }) => (
<li>
<input type="checkbox" name="" />
<span>{Name}</span>
<span></span>
<span>{Cost}</span>
</li>
);
Then in your render:
const { items } = this.props;
return (
<div className="container">
<a href="/products">Continue shopping</a>
{items.map(({ Name, Cost }) => <Product {...{Name, Cost}}/>}
</div>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With