Reputation: 11
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>
Upvotes: 1
Views: 174
Reputation: 3476
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
Upvotes: 0
Reputation: 20755
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>
Upvotes: 1
Reputation: 690
You can use the same approach as with your select
.
For example:
<div className="box">
{
this.state.selected.map(item => (
<Button ...>
))
}
</div>
Upvotes: 0