2

I'm trying to make a form in ReactJS. https://facebook.github.io/react/docs/forms.html, for instance, tells how to create a UI element, where changing the value of the element will trigger XYZ where the object on which an event occurs has access to the input and therefore its comments.

Suppose that, within the same larger component, I have a TEXTAREA to enter data in, and a button to click to save it.

How do I do things right so that a click to the button creates a new blank record and initializes its "description" field to the content of the TEXTAREA?

Thanks,

1 Answer 1

2

There are many ways that you could do this. A naive implementation (ignoring flux and kin) would look like the following:

var React = require('react');

class Form extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {description: ''};
    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChange(e) {
    this.setState({[e.target.name]: e.target.value});
  }

  onSubmit(e) {
    e.preventDefault();
    fetch(this.props.formAction, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        description: this.state.description
      })
    });

    this.setState({description: ''});
  }

  render() {
    return (
      <form action={this.props.action} method={this.props.method} onSubmit={this.onSubmit}>
        <textarea onChange={this.onChange} name="description">
          {this.state.description}
        </textarea>
        <button>Submit</button>
      </form>
    );
  }
}

Form.propTypes = {
  action: React.PropTypes.string.isRequired,
  method: React.PropTypes.string,
}

Form.defaultProps = {
  action: '/action/url',
  method: 'post',
};

module.exports = Form;

Use React’s Component methods setState to manage your application data. When onSubmit is called, prevent the browser default behavior with your ajax’d version of the same.

If using Flux, that fetch call would be an Action instead.

Sign up to request clarification or add additional context in comments.

3 Comments

flux and kin? what is it?
Flux is an application architecture. MVC and kin (MVC, MVVM, MV* in js-land) are other popular alternatives. facebook.github.io/flux
This comment doesn't mention that you need to bind this on the onChange and onSubmit functions ( facebook.github.io/react/docs/… )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.