0
votes

I'm encountering a weird problem and I have no idea what is going on. I used the exact same code before but now it's behaving differently. Maybe I'm overlooking something. What I want: For the purpose of my question here: I want to render a select input with three options. One of those options is a "disabled defaultValue" option, which is supposed to be a placeholder. The other two options have a value and the select has a value that is a state i'm passing it to.

So I'm rendering the form like so (I'm keeping it short here in order to have a clean look):

<Form
  is_expenditure={this.state.is_expenditure}
/>

I have the state defined, it's empty. Then I have my Form component like so:

class Form extends React.Component{
  render() {
return (
  <div>
    <form>
      <select value={this.props.is_expenditure}>
        <option disabled defaultValue>Ehne mehne Muh</option>
        <option value="1">Test</option>
        <option value="2">Test 2</option>
      </select>
    </form>
  </div>
)
  }
};

And whenever the component renders the option with value=1 is preselected. If I refresh the page with the browser, the select input suddenly has the defaultValue. But whenever I first start up the dev server and look at the form it has a preselected value... even though the state is definitely empty. Has someone an idea? This is really bothersome. I cut it short here but I had several select inputs and they all had preselected the value=1 option. The weird thing was that when I changed the first select input to a value the other select inputs on the page changed to the defaultValue...

EDIT

It seems like the "disabled" part in the option will keeps it from being selected on render. I'm pretty sure this worked before, did a newer react version disallow this? Is there a workaround? All I want is to have a select input with a placeholder basically.

1

1 Answers

0
votes

The problem is the disabled prop. Browser will ignore that option and it cannot be selected that's why the other options got selected by default. You can handle this empty state while saving it to the state

class Form extends React.Component{
  render() {
return (
  <div>
    <form>
      <select value={this.props.is_expenditure}>
        <option defaultValue>Ehne mehne Muh</option>
        <option value="1">Test</option>
        <option value="2">Test 2</option>
      </select>
    </form>
  </div>
)
  }
};

ReactDOM.render(<Form/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>