Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


React Forms

Handling forms is about how you handle the data when it changes value or gets submitted.

In HTML, form data is usually handled by the DOM.

In React, form data is usually handled by the components.

When the data is handled by the components, all the data is stored in the component state.

You can control changes by adding event handlers in the onChange attribute:

import React from 'react';

class Form extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         firstName: 'Folau'
      }
      this.updateState = this.updateState.bind(this);
   };

   updateState(e) {
      this.setState({firstName: e.target.value});
   }

   render() {
      return (
         <div>
            <input type = "text" value = {this.state.firstName} 
               onChange = {this.updateState} />
            <h4>{this.state.firstName}</h4>
         </div>
      );
   }
}
export default Form;

You must initialize the state in the constructor method before you can use it.

You get access to the field value by using the event.target.value syntax.

Submitting Form

You can control the submit action by adding an event handler in the onSubmit attribute.

import React from 'react';
import ReactDOM from 'react-dom';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
    };
  }
  mySubmitHandler = (event) => {
    event.preventDefault();
    alert("You are submitting " + this.state.username);
  }
  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    this.setState({[nam]: val});
  }
  render() {
    return (
      <form onSubmit={this.mySubmitHandler}>
      <h1>Hello {this.state.username} {this.state.age}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />
      <p>Enter your age:</p>
      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />
      <input
        type='submit'
      />
      </form>
    );
  }
}

ReactDOM.render(<Form />, document.getElementById('root'));

 

Note that we use event.preventDefault() to prevent the form from actually being submitted.

 It’s convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called “controlled components”.

 

 

August 6, 2019

React Events

Just like HTML, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover etc.

A good practice is to put the event handler as a method in the component class:

class Profile extends React.Component {
  changeName() {
    alert("name changed!");
  }
  render() {
    return (
      <button onClick={this.changeName}>change your name!</button>
    );
  }
}

ReactDOM.render(<Profile />, document.getElementById('root'));

Bind this

For methods in React, the this keyword should represent the component that owns the method. That is why you should use arrow functions. With arrow functions, this will always represent the object that defined the arrow function.

class Profile extends React.Component {
  changeName = () => {
    alert(this);
    /*
    The 'this' keyword refers to the component object
    */
  }
  render() {
    return (
      <button onClick={this.changeName}>change your name!</button>
    );
  }
}

ReactDOM.render(<Profile />, document.getElementById('root'));

Why use arrow function?

In class components, the this keyword is not defined by default, so with regular functions the this keyword represents the object that called the method, which can be the global window object, a HTML button, or whatever.

Read more about binding this in our React ES6 ‘What About this?’ chapter.

If you must use regular functions instead of arrow functions you have to bind this to the component instance using the bind() method:

Passing parameters

If you want to send parameters into an event handler, you have two options:
Make an anonymous arrow function

class Profile extends React.Component {
  changeName = (a) => {
    alert(a);
  }
  render() {
    return (
      <button onClick={() => this.changeName("Goal")}>Change your name!</button>
    );
  }
}

ReactDOM.render(<Profile />, document.getElementById('root'));

Bind the event handler to this. Note that the first argument has to be this.

class Profile extends React.Component {
  changeName(a) {
    alert(a);
  }
  render() {
    return (
      <button onClick={this.changeName.bind(this, "Lau")}>change your name!</button>
    );
  }
}

ReactDOM.render(<Profile />, document.getElementById('root'));

Note: If you send arguments without using the bind method, (this.shoot(this, "Goal") instead of this.shoot.bind(this, "Goal")), the shoot function will be executed when the page is loaded instead of waiting for the button to be clicked.

It is generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.

 

Arrow Function onClick

Remember that props are evaluated before they’re passed down. When written without the arrow function, a link or button would be called when ui renders, instead of when the link is clicked. That’s not what we want. Wrapping it in an arrow function delays execution until the user clicks the link.

 

August 6, 2019

React Lifecycle

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases. The three phases are: MountingUpdating, and Unmounting.

Mounting

Mounting means putting elements into the DOM.

React has four built-in methods that gets called, in this order, when mounting a component:

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

The render() method is required and will always be called, the others are optional and will be called if you define them.

Constructor

The constructor() method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values.

The constructor() method is called with the props, as arguments, and you should always start by calling the super(props) before anything else, this will initiate the parent’s constructor method and allows the component to inherit methods from its parent (React.Component).

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "Folau"};
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Profile />, document.getElementById('root'));

getDerivedStateFromProps

The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props. It takes state as an argument, and returns an object with changes to the state.

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: ""};
  }
  static getDerivedStateFromProps(props, state) {
    return {name: props.name };
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Profile name="Folau"/>, document.getElementById('root'));

render()

The render() method is required, and is the method that actually outputs the HTML to the DOM.

componentDidMount

The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already placed in the DOM.

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "Folau"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({name: "Lisa"})
    }, 1000)
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Profile />, document.getElementById('root'));

 

Updating

The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the component’s state or props.

React has five built-in methods that gets called, in this order, when a component is updated:

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

The render() method is required and will always be called, the others are optional and will be called if you define them.

 

August 6, 2019

React State

React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders. State is similar to props, but it is private and fully controlled by the component.

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "Folau"
    };
  }
  render() {
    return (
      <div>
        <h1>My name is {this.state.name}</h1>
      </div>
    );
  }
}

Change state

To change a value in the state object, use the this.setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s). 

class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "Folau"
    };
  }
  changeName = () => {
    this.setState({name: "Lisa"});
  }
  render() {
    return (
      <div>
        <h1>My name is {this.state.brand}</h1>
        <button
          type="button"
          onClick={this.changeName}
        >Change Name</button>
      </div>
    );
  }
}

Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods).

Don’t change state directly

this.state.comment = 'Hello';

August 6, 2019

React Props

Props are like function arguments, and you send them into the component as attributes. Props are passed to components via HTML attributes. React Props are like function arguments in JavaScript and attributes in HTML Passing props is how information flows in React apps, from parents to children.

To send props into a component, use the same syntax as HTML attributes:

const homeElement = <Home name="Folau" />;
class Home extends React.Component {
  render() {
    return <h2>Hi, my name is {this.props.name}!</h2>;
  }
}

 

Pass data

class Home extends React.Component { 

  render() { 
   return <h2>I am a {this.props.userInfo.name}!</h2>; 
  } 
} 

class Profile extends React.Component { 
  render() { 
   const userInfo = {name: "Folau"}; 
   return ( <div> <Home userInfo={carinfo} /> </div> ); 
  } 
} 

ReactDOM.render(<Profile />, document.getElementById('root'));

What Exactly Should Be Passed as a Prop?

Props can accept all sorts of things: Numbers, Booleans, Strings, Objects, even Functions. Early on you might start to wonder, should you pass an object and let the component extract what it needs? Or should you pass the specific pieces of data that the component requires?

You won’t use all of an object attributes in most cases.

It’s a good idea to keep the knowledge of data structures contained to as few places as possible to reduce the cost of change.

Props in Constructor

If your component has a constructor function, the props should always be passed to the constructor and also to the React.Component via the super() method.

React Props are read-only! You will get an error if you try to change their value.

Communicating With Parent Components

If you can’t change props, but you need to communicate something up to a parent component, how does that work?

If a child needs to send data to its parent, the parent can inject a function as a prop, like this:

function handleAction(event) {
  console.log('Child did:', event);
}

function Parent() {
  return (
    <Child onAction={handleAction}/>
  );
}

function Child({ onAction }) {
  return (
    <button onClick={onAction}/>
  );
}

The Child component receives a prop named onAction, which it can call whenever it needs to send up data or notify the parent of an event. You’ll notice that the built-in button element accepts an onClick prop, which it’ll call when the button is clicked. 

August 6, 2019