Using List
We are going to create something like this:
By clicking the add
button, it will add an item into the list, and by clicking the item itself, it will be removed.
We will have a contain class component MyContainer
that keep the list and state, and item functional component ItemComponent
for each item on the list.
MyContainer
This container is the heart of this example. It contains a state
, and two callback functions for adding and deleting the item. For the render function, we can keep on using JSX. Here we use map
function to loop through the list and obtain the index, and build up the list UI. The addItems
and deleteItem
are use as callback to manipulate the state
. We have talked about state
in the previous page, and not going to repeate here.
import React, {Component} from "react"; import InnerComponent from "./InnerComponent"; import ItemComponent from "./ItemComponent"; class MyContainer extends Component { state = { items: [{name: "item1", price: 1.1, key: 1}, {name: "item2", price: 2.1, key: 2}, {name: "item3", price: 3.1, key: 3}, {name: "item4", price: 4.1, key: 4}, {name: "item5", price: 5.1, key: 5} ], count: 5 }; deleteItem = (index) => { this.setState((prevState, props) => { const newItems = [...prevState.items]; newItems.splice(index, 1); return { items: newItems } }); }; addItems = () => { this.setState((prevState, props) => { const newItems = [...prevState.items]; let count = prevState.count + 1; newItems.push({name: "item" + count, price: count + 0.1, key: count}); return { items: newItems, count: count } }); }; render() { const items = this.state.items.map((item, index) => { return (<ItemComponent name={item.name} price={item.price} index={index} clickHandler={() => this.deleteItem(index)} />) }); return ( <div> {items} <button onClick={this.addItems}>Add</button> </div> ) } } export default MyContainer;
Other Than Using map function
There are multiple way to do the looping, we can use for … in
or forEach
to achieve the same result. It is just personal preference to use which.
let items = []; let index = 0; for (const item of this.state.items) { items.push(<ItemComponent name={item.name} price={item.price} index={index} clickHandler={() => this.deleteItem(index)}/>) index++; }
let items = []; this.state.items.forEach(function (item, index) { items.push(<ItemComponent name={item.name} price={item.price} index={index} clickHandler={() => this.deleteItem(index)}/>) });
ItemComponent
Item component is very simple, we only need to display the info from the prop
, and hook up the onClick event.
import React from "react"; const ItemComponent = (prop) => { return ( <div key={prop.index} onClick={prop.clickHandler}> name: {prop.name}, price: ${prop.price}, key: {prop.index} </div> ); }; export default ItemComponent;