1

Here is the code for generating the options manually. Is there anyway to populate the options dynamically from an array or json

    return React.createElement("select", {},
      React.createElement("option", {value: "A"}, "Option A"),
      React.createElement("option", {value: "B"}, "Option B"),
      React.createElement("option", {value: "C"}, "Option C")
    );
  }

2 Answers 2

1

I'd highly recommend compiling JSX, and you can easily use .map where the callback returns a component:

const values = ['A', 'B', 'C'];
// ...
return (
  <select>
    {values.map(val => <option value={val}>{val}</option>)}
  </select>
);

If you can't use JSX (though you really should for anything remotely serious, since it makes syntax much easier), you can spread the result into createElement instead.

return React.createElement("select", {},
  ...values.map(value => React.createElement("option", { value }, value))
);
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks for the insanely fast reply. Worked like a charm
0
const values = ['A', 'B', 'C'];
// ...
return (
  <select>
    {values.map((val, i) => <option key={i} value={val}>{val}</option>)}
  </select>
);

Don't forget to add key prop as React will complain about it

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.