JSX React HTML5 Input Slider Doesn't Work

CodeFromthe510 picture CodeFromthe510 · Mar 21, 2016 · Viewed 39.2k times · Source

I'm using React.JS for a build, and am building a range input slider with two choices for a component.

this is my code:

<input id="typeinp" type="range" min="0" max="5" value="3" step="1"/>

When I place it into my client side rendering component and try to toggle it it does not move at all. Testing it onto a JS/PHP build I have going on, it works fine.

Why does this not work in JSX/React.JS and what would be a suggested work around?

Thanks!

Answer

xCrZx picture xCrZx · Mar 21, 2016

User interactions have no effect because an <input> with value prop is considered as controlled. It means that displayed value is controlled entirely by render function. So to actually update input value you should use the onChange event. Example:

getInitialState: function() {
  return {value: 3};
},
handleChange: function(event) {
  this.setState({value: event.target.value});
},
render: function() {
  return (
    <input 
      id="typeinp" 
      type="range" 
      min="0" max="5" 
      value={this.state.value} 
      onChange={this.handleChange}
      step="1"/>
  );
}

You can also use defaultValue instead of value. In this case <input> is considered as uncontrolled and any user interactions are immediately reflected by element itself without invoking render function of your component.

More on this in official documentation