0

I know, there is one related question at Stackoverflow Link

  • But I'm facing issues with setting defaultValue.
  • value with onChange works
  • Even with defaultValue="m" or defaultValue="f" also works
  • But while setting defaultValue dynamically is not working.
// value of member.gender is 'f' and confirmed from console.log
<div className="col-3">
  <select name="gender" id="id_gender" defaultValue={member.gender}>
    <option value="m" >Male</option>
    <option value="f">Female</option>
  </select>
</div>
  • value of member.gender is "f" but always Male i.e. first option gets selected.
  • tried to quote {member.geder} using "${member.gender}" enclosed in ticks not working.
  • I'm using useRef based approach, to let form behave as an uncontrolled component. Therefore need to provide defaultValue to select element.
2
  • If it's an uncontrolled component, then you don't need to provide a defaultValue. DOM handles it. That's why we called it uncontrolled components. Commented May 31, 2021 at 4:49
  • When you select a different option, DOM updates the UI of select automatically. Commented May 31, 2021 at 4:55

2 Answers 2

1

Reactjs Library provides two options to handle form elements.

  1. Controlled Components - If you need to change something in UI according to the form value, use this option.
import { Component } from "react";

class App extends Component {
  state = {
    gender: "",
  }; // Step 1 - Create a property related to `select` form element in state object

  onChange = (e) => {
    const val = e.target.value;
    e.preventDefault();
    this.setState(() => ({
      gender: val,
    })); // Step 5 - You can update the value by using `setState` 
  }; // Step 3 - Create a method for `select` form element onChange event

  render() {
    return (
      <div className="col-3">
        <select
          name="gender"
          id="id_gender"
          value={this.state.gender} {/* Step 2 - Set that `select` related state property to value attribute */}
          onChange={this.onChange} {/* Step 4 - Set that method to onChange event */}
        >
          <option value="m">Male</option>
          <option value="f">Female</option>
        </select>
      </div>
    );
  }
}

export default App;
  1. Uncontrolled Components - If you just need to form data to save in a database, then you can use this option.
import { Component, createRef } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.selectEle = createRef(); // Step 1 - Create the reference
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit = (e) => {
    e.preventDefault();
    alert(this.selectEle.current.value); // Step 3 - You can access to the value like this.
  };

  render() {
    return (
      <div className="col-3">
        <select name="gender" id="id_gender" ref={this.selectEle}> {/* Step 2 - Add the reference to `select` element */}
          <option value="m">Male</option>
          <option value="f">Female</option>
        </select>
        <button type="submit" onClick={this.onSubmit}>
          Submit
        </button>
      </div>
    );
  }
}

export default App;
Sign up to request clarification or add additional context in comments.

7 Comments

But this does not solve the problem at hand. If we use value only, either we need to prove onChange or we cannot change the selected option at all. I am looking for a way to selected the defaultValue, but you have not given any clue for that.
These are officially recommended ones. So its better if you can update your code into one of these options.
I'm following the Uncontrolled Components-based approach. So need to set a default value, as this form is used to update an existing model instance. If I provide defaultValue="m" or defaultValue="f" it works well. But I need to set the default value dynamically based on the current state of the model instance. There seems to be some issue with JSX expression being used.
Check my explanations about Controlled & Uncontrolled components. If you want to control the select element UI then you have to use Controlled Components option. Don't make it complicated by using the wrong option. Always try to follow best practices.
If you use Controlled Components option, you can change selected option easily as mentioned above.
|
0

Instead of defining defaultValue or selected on each option, you can write value={member.gender} on the select tag itself:

<div className="col-3">
  <select name="gender" id="id_gender" value={member.gender}>
    <option value="m" >Male</option>
    <option value="f">Female</option>
  </select>
</div>

1 Comment

As I mentioned in the question description and comment on another answer, this approach requires me to use state and a function to handle the onChange event, which I don't want to do.

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.