Dealing With State In
OnSubmit React

- 1 answer

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) {
  handleSubmit: function(event) {
    $.post('/test', { data: this.state.value }).done(function(data) {
  render: function() {
    var placeholder = this.state.placeholder;
    return (
        <form onSubmit={this.handleSubmit}>
          <input type="text" placeholder={placeholder} onChange={this.handleChange} />
          <button> smithy</button>

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.



in your render() function, you never specify what value should be displayed inside your <input> element. When your component is rendered for the first time, it's empty; when your component is rendered subsequent times, React's behind-the-scenes DOM-diffing code does not detect any changes to the <input> element and therefore doesn't rebuild it (meaning whatever it contained before, it still contains now).

if you want to clear the <input> after form submit, you'll need to clear state.value inside of handleSubmit(), and then tell <input> to show state.value inside of render().