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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.