Matty
Matty

Reputation: 11

React Select menu - Select multiple items - Advanced

I have to make a select menu in react but there is an extra couple functions it needs to have that I haven’t been able to find on the first 50 links of google. (I’m not googling the right thing obviously cause idk what it’s called).

Details:

A select menu that, once an item is selected, carries the item far below the select menu so that the item can be manipulated further. For example, I want to select multiple ingredients and then have them displayed on the same page, in order of selection, and then be able to enter an amount in a text field that is next to the ingredient that has been selected.

Process:

Select paprika (remove paprika from select menu because there is no need to select it again) > see paprika appear far below select menu > enter amount of paprika in text field tied to back end > repeat for other ingredients.

Any help would be greatly appreciated. Even if you just tell me what to google.

Thank you all,

Matt

Upvotes: 1

Views: 544

Answers (2)

Seth McClaine
Seth McClaine

Reputation: 10040

I tried to write this up in JSFiddle but it was tripping out on me.... Here should be an Almost working example with the same approach that Joss mentioned. I think you'll be able to get the idea from it

class Demo extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        selected: [],
    };
  }

  select(e) {
    const { value } = e.currentTarget;
    let { selected } = this.state;
    if(selected.contains(value)) {
        selected = selected.filter((val) => val !== value);
    } else {
        selected.push(value);
    }
    this.setState({
        selected,
    });
  }

  render() {
    const ret = []; //Just using this to map over to create options
    for(i = 0; i < 5; i++) {
        ret.push(i);
    }

    return (
    <div className="container">
    { ret.map((i)=>(
      <div
          onclick={this.select}
          value={i}
          className={this.state.selected.contains(i) ? 'selected' : null}>
            {i}
          </div>
      )}
    </div>
    );
  }
}

ReactDOM.render(
  <Demo />,
  document.getElementById('container')
);

Upvotes: 2

Joss Classey
Joss Classey

Reputation: 1062

I would have an array stored in state that would contain all selected ingredients, which would be updated each time a new ingredient is selected (using onChange). I would then simply use this array to influence what is displayed on the rest of the page.

Upvotes: 1

Related Questions