Florent Destremau Florent Destremau - 25 days ago 7
React JSX Question

Is there a simpler way of creating an array with a single element or empty if the element is null?

I somehow find it pretty lame to write the selection initialization:

updateSelectType(event) {
this.setState({
selectType: event.target.value,
selection: this.state.selectedEvent ? [this.state.selectedEvent] : [],
selectedEvent: null,
});
}


So this is pretty straightforward, I wonder if the ternary can be simplified ? I don't want an array with a
null
element :)

Answer Source

You can try this approach

updateSelectType(event) {
  this.setState({
   selectType: event.target.value,
   selection: [this.state.selectedEvent].filter(el => el),
   selectedEvent: null,
  });
}