Jack BeNimble
Jack BeNimble

Reputation: 36643

How to create and use a map in ReactJS

I have a Spring-Boot app with a ReactJS front-end, and I'm trying to figure out how to use Semantic UI to use a value selected from one input field to populate another input field.

I think I have most of the pieces in place, but I'm trying to figure out how to select a value from an array of name/value objects based on the name. I haven't quite gotten how the "map" function works, and the examples I've seen so far choose based on an index rather than a value. How to code it so it chooses the entry based on the value?

For example, here's the array:

const productMap = [
  {key: 'template_key1', value: 'Product 1'},
  {key: 'template_key2', value: 'Product 2'},
  {key: 'template_key3', value: 'Product 3'}
}

I have a method that gets called when the user selects the key:

 handleSelectTemplateChange=(event,{value})=>{
    let item = {...this.state.item};
    item.template = value;

    // how should this be coded?  
    item.product = productMap.getValue(item.template); 

    this.setState({item});
  }

Upvotes: 0

Views: 32

Answers (2)

gdh
gdh

Reputation: 13682

You can use array find too. It is ideal to use find instead of map/forEach because we don't need to map over all the array elements once we find desired product.

const productMap = [
  { key: "template_key1", value: "Product 1"},
  { key: "template_key2", value: "Product 2" },
  { key: "template_key3", value: "Product 3" },
];

handleSelectTemplateChange = (event, { value }) => {
  let item = { ...this.state.item };
  item.template = value;
  const productValue = productMap.find((product) => product.key === value);
  item.product = productValue.value;
  this.setState({ item });
};

Upvotes: 1

Jack BeNimble
Jack BeNimble

Reputation: 36643

I found a good description at this site.

Here's the code that seems to work:

   item.template = value;
    productMap.map(entry =>{
      if (value === entry.key){
        item.product = entry.value; 
      }
    })

Upvotes: 0

Related Questions