Pup

v2.x

ReactForms

Forms in Pup are kept relatively simple. Third-party libraries are avoided in favor of using plain HTML <form> tags with submission being handled via an onSubmit attribute on the <form> —or, like the example on the right, the submitHandler function on the form's validation—and a button with a type="submit" attribute inside of the<form>.

On the right, a simple example of a React component containing a form is presented.

A few things to note: first, the Validation component from Pup is being imported to add client-side validation to the form. This allows us to validate the user's input before submitting the form to ensure they've completed it properly.

Notice that the <form>'s onSubmit attribute is set to a function returning a call to event.preventDefault(). This is telling the form to not submit using the browser's default submission technique of performing a POST request to a URL defined by the form's action attribute (not used when performing a form submission via JavaScript).

Instead, the <Validation /> component here is attaching to the form's submission process and replacing it with the function passed to the submitHandler prop on the component.

In this case, when the form is submitted—assuming the user has passed the required validation—submitHandler is called which then relays the call to the handleSubmit function defined on the <CreatePersonForm /> component, passing along the <form> being submitted.

Inside of handleSubmit, the presumed mutation method provided to us via GraphQL using the graphql() component enhancer function from the react-apollo package then makes a call to our createPerson mutation in our GraphQL schema.

Example Form Component
import React from 'react';
import { graphql } from 'react-apollo';
import { FormGroup, ControlLabel, Button } from 'react-bootstrap';
import Validation from '../Validation';
import { createPerson as createPersonMutation } from '../../mutations/People.gql';

class CreatePersonForm extends React.Component {
  handleSubmit = (form) => {
    this.props.createPerson({
      variables: {
        name: form.name.value.trim(),
      }
    });
  }

  render() {
    return (
      <Validation
        rules={{
          name: {
            required: true
          }
        }}
        messages={{
          name: {
            required: "What's your name, friend?"
          }
        }}
        submitHandler={(form) => {
          this.handleSubmit(form);
        }}
      >
        <form onSubmit={(event) => event.preventDefault()}>
          <FormGroup>
            <ControlLabel>Name</ControlLabel>
            <input type="text" name="name" className="form-control" />
          </FormGroup>
          <Button type="submit" bsStyle="success">Create Person</Button>
        </form>
      </Validation>
    );
  }
}

export graphql(createPersonMutation, {
  name: 'createPerson',
})(CreatePersonForm);