Skip to content

Instantly share code, notes, and snippets.

@ohnomalone
Created November 25, 2019 23:41
Show Gist options
  • Save ohnomalone/1a5015c18a3fa581007a4f70e28ca5bc to your computer and use it in GitHub Desktop.
Save ohnomalone/1a5015c18a3fa581007a4f70e28ca5bc to your computer and use it in GitHub Desktop.

Building a Form Component in React

  • Form needs to have state and because of that it will need to be a class. The state will hold and updat as the user types in the input fields.

The cyclical nature of state in a From Component.

This is an example to build a simple form taking in a users info including:

  • First Name
  • Last Name
  • Email
  • Phone Number

Page Setup

  1. Import React
  • React has to be imported
import React from 'react'
  1. Extend Class
  • Extend the class from React component (this gives the class access to all the methods availabe from React)
  • constructor() - since this is a class we need a constructor. Typically nothing is passed through this constructor since this form is only outputting information, not taking any in.
  • super() - to pull in all methods of the class we are extending we need super.
  • state is needed for our information to live.
export class Form extends React.Component {
  constructor() {
    super();
    this.state = {
    };
  }
  1. Export the form
  • The form has to be exported so that the component can be used in other components of the app.
export default Form;
  1. Render & Return
  • This is a class and all React Components that are classes need the render method
  • render() lives within the class componet, at the bottom. All other methods crated will be below the constructor and above render.
  • Return lives inside the Render method and contains the built out form using JSX.
render() {
  return(
    <form className='Form'>
      <label htmlFor="firstName" className="UserModalFormLabel">
        Name
      </label>
      <input
        className="UserForm"
        id="firstName"
        type="text"
        name="firstName"
        placeholder="First Name"
        onChange={this.handleChange}
        value={this.state.name}
      />
       <label htmlFor="lastName" className="UserModalFormLabel">
        Name
      </label>
      <input
        className="UserForm"
        id="lastName"
        type="text"
        name="lastName"
        placeholder="Last Name"
        onChange={this.handleChange}
        value={this.state.name}
      />
       <label htmlFor="email" className="UserModalFormLabel">
        Name
      </label>
      <input
        className="UserForm"
        id="email"
        type="email"
        name="email"
        placeholder="E-mail"
        onChange={this.handleChange}
        value={this.state.name}
      />
      <label htmlFor="phoneNumber" className="UserModalFormLabel">
        Name
      </label>
      <input
        className="UserForm"
        id="phoneNumber"
        type="tel"
        name="phoneNumber"
        placeholder="Phone Number"
        onChange={this.handleChange}
        value={this.state.name}
      />
       <button
          type="button"
          className="UserFormBtn"
          onClick={() => this.handleSubmit()}
        >
          Submit
        </button>
    </form>
  )
}

Methods

handleChange()

As the user types into the inputs fields, state needs to be updated to do that. A common method to do this is handleChange(). onChange={} within within each input will fire off this method with the event attached. value={this.state.name} is set to the current state of the of whichever input that is is in, which will be see in the handleChange() method.

handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

handleChange() is written so that it will work with all four input fields. The event being passed through contains both a name and value (name and value are setup in the input tags). No matter which input is being used handleChange() will update the appropiate property in state.

handleSubmit()

Wherever the user information is going to live, when the user hits the submit button we need to move it there. This is done through the handleSubmit() method.

  • if this is passed down in props you can either call it but using dot notation or deconstructing it in the method you want to use. ex. this deconstructs the prop, creates the new idea using the spread operator and adding an id with Date.now(), envoking addIdea and resetInputs to clear out the input fields by resetting state.
 handleSubmit = event => {
    event.preventDefault();
    const { addIdea } = this.props;
    const newIdea = { ...this.state, id: Date.now()};
    addIdea(newIdea);
    this.resetInputs();
  }

  resetInputs = () => {
    this.setState({ 
      title: '',
      description: ''
    })
  }

the render methods associated with this is as follows:

render() {
  return (
    <form>
      <input
        type='text'
        placeholder='title'
        value={this.state.title}
        name='title'
        onChange={this.handleChange}
      />
      <input
        type='text'
        placeholder='description'
        value={this.state.description}
        name='description'
        onChange={this.handleChange}
      />
      <button 
        onClick={this.submitNewIdea}
      >
        Submit!
      </button>
    </form>
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment