So I'm starting to play around with React and am trying to wrap my head around state. I'm running into this issue with an onSubmit action on a form where it doesn't clear the input field after it's triggered. A fairly trivial issue, but I feel like there's a broader lesson in here about the whole component interacts that I'm missing.
'use strict'
const SmithyForm = React.createClass({
displayName: "SmithyForm",
getInitialState: function() {
return { placeholder: "tweet" };
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
handleSubmit: function(event) {
$.post('/test', { data: this.state.value }).done(function(data) {
console.log(data)
});
event.preventDefault();
},
render: function() {
var placeholder = this.state.placeholder;
return (
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder={placeholder} onChange={this.handleChange} />
<button> smithy</button>
</form>
);
}
})
ReactDOM.render(<SmithyForm />, document.body )
So, my question is: What about my structure is preventing onSubmit from clearing the input field? (The code itself all works, component renders a form with a button. When the button is clicked the form makes an ajax request to a Node/Express backend which sends back the text entered into the input field.)
EDIT/ANSWER: The two pieces I missed were a default value: "" set in the getInitialState function and the subsequent call to that state in the render function var value = this.state.value;
One thing I'm still not as clear on as I'd like to be—which @Dan was alluding to—is the rerendering process of the component after it onSubmit is triggered.
thisobject is wrong. keep a reference to it inside ofrender():var self = this;and then reference it inside your onChange attribute:onChange={self.handleChange}- Dan O