Skip to content Skip to sidebar Skip to footer

How Can I Dynamically Display What Appears In The Modal

The type of food selected shows up in the modal successfully upon clicking the appropriate button if I write in between

{this.state.cTaco}

Solution 1:

You are currently just using the keys of the items object. You want to get the value that the keys have in the state object.

<ModalisOpen={this.props.isOpen}><p>
    {Object.keys(this.state.items).map(key => (
      <pkey={key}>{this.state[key]}</p>
    ))}
  </p><buttononClick={() => this.props.closeModalRedux()}>Close</button></Modal>

Solution 2:

Your code is very messy. Your code structure is fixed, meaning that each taco type has to be declared individually and in different methods...

The main problem with your code is you have items in your state which you read from, but in the *Taco() methods and the chickenBurrito() method you set this.state.cTaco (for example) instead of this.state.items.cTaco.

But your code in general could and should be improved. How about instead of an individual method for each taco type you do the following:

Change your state structure to:

this.state = {
  selectedItem: '',
};

And declare the following object in your constructor:

this.items = {
  // If you'll have more attributes for each item, it's best that you set
  // each item as an objectwith a name and the other attributes.
  chickenTaco: 'Chicken Taco',
  beefTaco: 'Beef Taco',
  chickenBurrito: 'Chicken Burrito',
};

And then you can have one method instead of three (or however many items you have):

selectItem(item) {
  this.setState({selectedItem: item});
}

So now your Modal's contents will look like this:

{this.items.map(item => (<pkey={item}>{item}</p>)}

Far cleaner. This way the items are dynamic, and you can easily add attributes and items. In a real life use you'd probably get this information from the backend, where you can't anticipate which methods you need to create per items, or how many items you'll have (if any).

Post a Comment for "How Can I Dynamically Display What Appears In The Modal"