Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Select with default value from props without onChange event?

So, I was just wondering if I absolutely need to have a onChange event handler on a select component in React?

I have a prop passing in the default value on the option I want selected. It works no problem if I have:

<select 
  value={this.props.defaultValue}
>
  <option value="a">A</option>
  <option value="b">B</option>
</select>

Except, it is static as I am sure you are familiar with the error:

Warning: Failed form propType: You provided a `value` prop to a form field without an `onChange` handler. 
This will render a read-only field.

As I am getting the value using Jquery, I don't need a state or any passing between child and parent...

Is there a simple way to allow the select to get a default value from props and still operate as a normal select where changing an option changes the value I can grab with jquery, or do I have to have a state, and a onChange handler?

Thanks!

What I have already tried:

<select
  defaultValue={this.props.defaultValue} // just returns the first option
> 
  <options etc.>
</select>

Also, I would rather not use an external package like React-Select... I just want to have a default value and a normal select...

like image 601
Daltron Avatar asked Oct 29 '22 08:10

Daltron


1 Answers

As @julien mentions, you can use ref instead of JQuery to get the current value of the select in an uncontrolled component:

class MySelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = { currentValue: this.props.defaultValue };
  }

  updateValue() {
    this.setState({ currentValue: this.refs.myselect.value });
  }

  render () {
    return (
      <div>
        <div>
          <button className="current" onClick={this.updateValue.bind(this)}>{this.state.currentValue}</button>
        </div>

        <select ref="myselect" defaultValue={this.props.defaultValue}>
          <option value="a">A</option>
          <option value="b">B</option>
          <option value="c">C</option>
        </select>
      </div>
    );
  }
}

For the other part, defaultValue should work just as you were trying.

Check this example fiddle: https://jsfiddle.net/y64gbhf8/1/

like image 103
Carlos Martinez Avatar answered Nov 15 '22 05:11

Carlos Martinez