Edgars Šusts
Edgars Šusts

Reputation: 111

Is there a way to change selected option with help of function in React?

I have custom radio buttons and select with few options. By default only some of the options is displayed in select box. When i check any radio button then select options is changing to some other options. When i uncheck radio button then they are changing back to default select options. So far everything is fine. But if option is selected and then radio button is checked or unchecked again it will change select options like it usually does but it will not display first option or default value(which is first option). It will display second or third depends which one was chosen before. Its not jumping back to "Actions"

{!this.state.isAnySelected ?
  <>
    <select defaultValue="Actions">
      <option>Actions</option>
      <option>Category request</option>
      <option>Add new review</option>
    </select>
  </>
  :
  <>
    <select defaultValue="Actions">
      <option>Actions</option>
      <option>Add new product</option>
      <option>View product</option>
    </select>
  </>
}

I tried to change defaultValue every time when radio button is clicked but it does nothing.

Upvotes: 0

Views: 384

Answers (2)

Ryan Cogswell
Ryan Cogswell

Reputation: 81036

One way to handle this is to add a key to the two select elements:

{!this.state.isAnySelected ?
  <>
    <select key="categorySelect" defaultValue="Actions">
      <option>Actions</option>
      <option>Category request</option>
      <option>Add new review</option>
    </select>
  </>
  :
  <>
    <select key="productSelect" defaultValue="Actions">
      <option>Actions</option>
      <option>Add new product</option>
      <option>View product</option>
    </select>
  </>
}

The effect of this will be to re-mount the select whenever this.state.isAnySelected changes.

Currently when this.state.isAnySelected changes, React will just be updating the option text of the existing options, so the currently selected index is unaffected. The "defaultValue" is only going to affect what is selected when the element is first mounted. The two different keys cause React to treat these as separate DOM elements rather than as changes to existing DOM elements, so whenever this.state.isAnySelected changes, the previous select will be unmounted and the other mounted with the correct default.

Upvotes: 1

Ganapati V S
Ganapati V S

Reputation: 1661

Yes, You can use controlled form elements in react. you need to keep track of value prop, pass it instead of defaultValue to make it work.

Solution here 👇

Edit 3vj6vymqjp

Upvotes: 2

Related Questions