Search code examples
reactjstypescriptreact-lifecycle

Update array of items with help of modal input in React


I didn't find any suitable answer for this question. Here is what I am looking for.

  • I have lists of menus items coming from the state array variable (https://i.sstatic.net/rOWg2.png).
  • I have an add button which opens a modal. Modal includes an input field. (https://i.sstatic.net/a0COe.png)
  • The final result would be when some click adds button of modal, its field values updated in menus state array. which further updates the menus list on UI.

I able to made all these UI. But I didn't have any idea how can I pass my data from modal input to menus list. Here is codesandebox link of the same problem (https://kx6yr.csb.app/).


Solution

  • So this is one way to do it, in your modals add this onAdd prop:

     <AddModal
      heading="Add Food"
      modalId="addFood"
      inputName="addFood"
      onAdd={(textEntered) => { alert(textEntered); }}
      ref={this.foodModal}
    />
    <AddModal
      heading="Add Drink"
      modalId="addDrink"
      inputName="addDrink"
      onAdd={(textEntered) => { alert(textEntered); }}
      ref={this.drinkModal}
    />
    

    And within the modal component, call this handler passing the input value:

        <button
          type="button"
          onClick={this.props.onAdd.bind(this, this.state.item)}
          className="golden-button-op"
          style={{ margin: "0px" }}
        >
          Add
        </button>
    

    Hope it helps!