Skip to content
Advertisement

How to make a select input that is dependent on other inputs to always show a default value in React?

I have two radio buttons: radio1 and radio2, and one select input. The Select values depend on the radio buttons. I want to set the select value to 1 whenever I select radio1. I’ve tried setting defaultValue and value to the select input but every time I switch back to radio1 from radio2, the value is always set to 2.

Here’s my code, any help is truly appreciated:

JavaScript

example: https://codesandbox.io/s/goofy-danny-p1l3s?file=/src/App.js:0-1460

Edit:

As suggested by some answers, I have tried setting ‘selected’ as true. In fact, I have tried this before and forgot to mention it on my question. This seem to work, it gives me the desired effect on the browser, but then I get this error on the console:

JavaScript

Advertisement

Answer

The main problem here is <option> is taking the same key value. When you are selecting radio2, key becomes 2.Then you are selecting radio1 and for that <select> has <option> with key=2. That is why <select> value not changing. The proof is if you change all <option> values unique, example for radio1 {1, 2} and for radio2 {3, 4, 5} your code works fine.

There may be multiple workarounds but the proper way to solve this is having unique id for each of the <option>.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement