guys, I am working on react js
I have created an input text and on blur of that input button I am calling a method and updating the state variable
but seem like if I use on blur instead of onChange then input text become read only field
<!DOCTYPE html>
<html>
<head>
<script data-require="react@*" data-semver="0.13.3" src="http://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script data-require="react-jsx@*" data-semver="0.13.1" src="http://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<link rel="stylesheet" href="style.css" />
<script type="text/jsx">
var App = React.createClass({
getInitialState: function () {
return {value: 'Hello!'};
},
changeTo: function (e) {
this.setState({value: e.target.value});
},
render: function () {
return (
<div>{this.state.value}
<input type="text" defaultValue={this.state.value || ''}
value={this.state.value} onBlur={(e) => this.changeTo(e)} />
</div>
);
}
});
React.render(
<App />,
document.getElementById('app')
);
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
You need to add onChange listener otherwise it will not work.
Reason: When you specify value={this.state.value} it means you are binding input text value to the variable value and react takes over the control for updating value in input box. By adding onChange listener, you tell react to call a component function to update value which basically updates the state of the component forcing it to call render function and updating the value in input text.
changeTo: function (e) {
this.setState({value: e.target.value});
},
updateValue: function (e) {
this.setState({value: e.target.value});
},
render: function () {
return (
<div>{this.state.value}
<input type="text" defaultValue={this.state.value || ''} value={this.state.value}
onBlur={(e) => this.changeTo(e)} onChange={(e) => this.updateValue(e}/>
</div>
);
}
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