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!
To get the HTML5 input slider working in React, we either set the value and onChange props or we can leave them both out. We add the value prop and set it to the value state. And we set the onChange prop to a function that calls setValue with e. target.
JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.
To use JavaScript inside of JSX, you need to surround it with curly braces: {} . This is the same as when you added functions to attributes. To create React components, you'll need to convert the data to JSX elements. To do this, you'll map over the data and return a JSX element.
As for whether it mimics HTML4 or HTML5, it depends on what you code, React itself is not limited to any HTML version and it is the browser that needs to worry about which HTML version you are using.
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
I think previous answers fix your problem. However, I'd say the solution doesn't need to involve React states.
The only reason behind your frozen input slider is that you've hardcoded its value to 3, as @Colin Whitmarsh suggests.
Simply, this works:
<input id="typeinp" type="range" min="0" max="5" defaultValue="3" step="1"/>
Now, you probably need its output to do something. You can use onChange={this.handleChange}
as @xCrZx states in his answer. But inside handleChange
you don't necessarily have to update your state. Depending on your logic, you could avoid increasing the complexity of your state and simply code your logic inside handleChange
.
If you avoid updating the state, you'll probably save some renders and your performance will improve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With