简体   繁体   中英

React: Rendering state array

I'm making a search form with React including a multiple select tag which adds selected options into a state as an array.

How do I successfully render selected items as a removable buttons into a box div?

class Search extends React.Component {
    constructor(props) {
        super(props)
        this.state = { selected: [] }
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange = e => {
        let item = e.target.value
        let selected = this.state.selected
        if (selected.includes(item)) {
            return null
        } else {
            selected.push({ item })
            this.setState({ selected: item })
        }
    }

    render() {
       const items = [ item1, item2, item3,... ]

    return(
       .....
       <select
           multiple={true}
           value={this.state.value}
           onChange={this.handleChange}>
           {items.map(item => (
              <option
                 key={item}
                 value={item}>
                 {item}
             </option>
           ))}
      </select>
      <div className="box">
      </div>

By doing this,

selected.push({ item })

You are actually pushing object to array, which should be just

selected.push( item )  //push item directly

Also you are setting state incorrectly,

this.setState({ selected: item })

You should only have,

this.setState({ selected })

And finally you can iterate over selected array like this,

<div className="box">
  { this.state.selected && this.state.selected.length > 0 && this.state.selected.map(selected=> <button key={selected}>{selected}</button>)
  }
</div>

Demo

You can use the same approach as with your select .

For example:

<div className="box">
   { 
     this.state.selected.map(item => (
        <Button ...>
     ))
   }
</div>

Make the item as object

const items = [ {item1:item1, isSelected: false}, {item2, isSelected: false},... ]

And when item select - toggle isSelected to true, and make some button if the item object.isSelected === true

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM