1

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>
0

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Omg this was so dumb mistake from me. facepalm Thank you, this worked!
0

You can use the same approach as with your select.

For example:

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

1 Comment

I already tried this, but it says this.state.selected.map is not a function.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.