Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to have second dropdown menu values be dependent on value of first dropdown menu in React render function

In the render function of a React component, I have the following code

            <select name="env" id="env">
              <option value="Dev">Dev</option>
              <option value="Staging">Staging</option>
              <option value="Prod">Prod</option>
            </select>
           

            <select name="region" id="region">
              <option value="option1">op1</option>
              <option value="option2">op2</option>
              <option value="option3">op3</option>
              <option value="option4">op4</option>
            </select>

If Dev option is selected in first dropdown, there should only be op1 choice available in the 2nd dropdown. Similarly if Staging is selected, then op1, op2 and op3 are the available choices. If Prod is selected, then all 4 choices are available. How can I achieve this in React?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should render different region options by env.

const regionsByEnv = {
  Dev: ["option1"],
  Staging: ["option1", "option2", "option3"],
  Prod: ["option1, option2, option3, option4"],
};

const YourComponent = () => {
  const [env, setEnv] = useState("");

  const regionOptions = useMemo(() => {
    if (!env) {
      return regionsByEnv.Prod.map((option) => (
        <option value={option} key={option}>
          {option}
        </option>
      ));
    }
    return regionsByEnv[env].map((option) => (
      <option value={option} key={option}>
        {option}
      </option>
    ));
  }, [env]);

  return (
    <>
      <select
        value={env}
        onChange={(e) => setEnv(e.target.value)}
        name="env"
        id="env"
      >
        <option value="Dev">Dev</option>
        <option value="Staging">Staging</option>
        <option value="Prod">Prod</option>
      </select>
      <select name="region" id="region">
        {regionOptions}
      </select>
    </>
  );
};

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading