0

I am looking for a better approach then simple if/else states to render out part of my app that requires conditional logic.

For example, if I have a <select> element that uses on an onChange to capture an event value like this:

<select onChange={(event) => setValue(event.target.value)}>

I know have my value set from my select using:

const [ value, setValue ] = useState(null);

Is there a way I can create logic that would set that value as part of my Object like this:

{
    data.<value>.map((item, index) => {
         return (
              <option key={ index }
                      value={ item.displayName }
              >
              { item.displayName }
              </option>
        );
    })
}

My data object has a bunch of various properties I want to use based on the value selected, and I didn't want to create a bunch of if/else or switch statements to try and render.

Any thoughts on a better approach?

zeropsi
  • 682
  • 9
  • 24
  • 1
    Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – David Aug 27 '21 at 16:39

1 Answers1

1

If I am not mistaken you are trying to dynamically access the properties in your "data" object. You can use the bracket notation to achieve that:

data[value].map((item, index) => {
     return (
          <option key={ index }
                  value={ item.displayName }
          >
          { item.displayName }
          </option>
    );
})

So now you don't need to know what is the name of the property to access. It will be dynamically accessed based on the value of your "value" state variable.

Juan Chaher
  • 523
  • 3
  • 9