React Forms - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Tuesday, September 29, 2020

React Forms

Forms in React is used to allow users to interact with the web page the same as HTML. This form has the default behavior of HTML  in which when the user submits the form we browse the new page. If you want this behavior to React, it just works. The standard way to achieve this is with a technique called “controlled components”.

How to Add Forms in React

You add a form with React just like any other element:

[code]

Example

form that allows users to enter their name:

class MyForm extends React.Component {

  render() {

    return (

      <form>

        <h1>Hello</h1>

        <p>Enter your name:</p>

        <input

          type="text"

        />

      </form>

    );

  }

}

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

[/code]

Handling Forms

It is about how you handle the data when it changes the value or submitted.

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

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

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:

To change and update the state object we add an event handler in the onChange attribute.

[code]

class MyForm extends React.Component {

  constructor(props) {

    super(props);

    this.state = { username: '' };

  }

  myChangeHandler = (event) => {

    this.setState({username: event.target.value});

  }

  render() {

    return (

      <form>

      <h1>Hello {this.state.username}</h1>

      <p>Enter your name:</p>

      <input

        type='text'

        onChange={this.myChangeHandler}

      />

      </form>

    );

  }

}

 

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

 [/code]

 

Conditional Rendering

If you do not want to display the header h1 element until the user has to insert any input, you can add an if statement.

Look at the example below and note the following:

1. We first create a variable, we call it a header.

2. We then add  if statement to insert content to the header variable if the user has any input.

3. Then we insert the header variable in the output, using curly brackets.

 

Displaying  the header only if username is defined:

[code]

class MyForm extends React.Component {

  constructor(props) {

    super(props);

    this.state = { username: ' ' };

  }

  myChangeHandler = (event) => {

    this.setState({username: event.target.value});

  }

  render() {

    let header = '';

    if (this.state.username) {

      header = <h1>Hello {this.state.username}</h1>;

    } else {

      header = '';

    }

    return (

      <form>

      {header}

      <p>Enter your name:</p>

      <input

        type='text'

        onChange={this.myChangeHandler}

      />

      </form>

    );

  }

}

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

[/code]

Submitting Forms

We can control the submit action by adding an event handler in the onSubmit attribute:

Example:

Add a submit button and an event handler in the onSubmit attribute:

[code]

class MyForm extends React.Component {

  constructor(props) {

    super(props);

    this.state = { username: ' ' };

  }

  mySubmitHandler = (event) => {

    event.preventDefault();

    alert("You are submitting " + this.state.username);

  }

  myChangeHandler = (event) => {

    this.setState({username: event.target.value});

  }

  render() {

    return (

      <form onSubmit={this.mySubmitHandler}>

      <h1>Hello {this.state.username}</h1>

      <p>Enter your name, and submit:</p>

      <input

        type='text'

        onChange={this.myChangeHandler}

      />

      <input

        type='submit'

      />

      </form>

    );

  }

}

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

[/code]

 

Validating Form Input

We can validate form input even when the user is typing or else you can wait till the form submitted.

Example:

When you enter your mobileno, you will receive an alert if the required field is not numeric:

[code]

class MyForm extends React.Component {

  constructor(props) {

    super(props);

      this.state = {

      username: ' ',

      mobileno: null,

    };

  }

  myChangeHandler = (event) => {

    let nm = event.target.name;

    let val = event.target.value;

    if (nm === "age") {

      if (!Number(val)) {

        alert("Mobile should be a number");

      }

    }

    this.setState({[nm]: val});

  }

  render() {

    return (

      <form>

      <h1>Hello {this.state.username} {this.state.mobileno}</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}

      />

      </form>

    );

  }

}

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

[/code]

Input Fields

We can control the values of more than one input field by adding a name attribute to each element. When you initialize the state in the constructor, use the field names. To access the fields in the event handler use the event.target.name and event.target.value syntax.

To update the state in this.setState method, use square brackets [bracket notation] around the property name.

[code]

Example:

Write a form with two input fields:

class MyForm extends React.Component {

  constructor(props) {

    super(props);

    this.state =

     {

     username: ' ',

      age: null,

    };

  }

  myChangeHandler = (event) => {

    let nm = event.target.name;

    let val = event.target.value;

    this.setState({[nm]: val});

  }

  render() {

    return (

      <form>

      <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}

      />

      </form>

    );

  }

}

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

 [/code]

Adding Error Message

React Forms apart from the HTML error message box is empty by default and displays the error when the user inputs anything invalid:

Example:

When you fill in your mobile no as not numeric, an error message is displayed:

 [code]

  class MyForm extends React.Component {

   constructor(props) {

    super(props);

    this.state = {

      username: ' ',

      mobileno : null,

      errormessage: ''

    };

  }

  myChangeHandler = (event) => {

    let nm = event.target.name;

    let val = event.target.value;

    let err = '';

    if (nm === "mobileno") {

      if (val !="" && !Number(val)) {

        err = <strong>Your mobile must be a number</strong>;

      }

    }

    this.setState({errormessage: err});

    this.setState({[nm]: val});

  }

    render() {

    return (

      <form>

      <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 mobile no:</p>

      <input

        type='text'

        name='age'

        onChange={this.myChangeHandler}

      />

      {this.state.errormessage}

      </form>

    );

  }

}

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

 [/code]

Textarea

The textarea element in React is little different from an ordinary HTML.

In HTML the value of a textarea is text between the start tag <textarea> and the end tag </textarea>

In React the value of a textarea is placed in a value attribute:

 Example:

A simple textarea with some content initialized in the constructor:

[code]

class MyForm extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      description: 'Textarea goes in the value attribute'

    };

  }

  render() {

    return (

      <form>

      <textarea value={this.state.description} />

      </form>

    );

  }

}

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

[/code]


Run Example

Select

A drop down list, or a select box, in React is also a bit different from HTML.

selected value in the drop down list was defined with the selected attribute:

[code]

HTML:

<select>

  <option value="Iphone">Iphone</option>

  <option value="Samsung" selected>Samsung</option>

  <option value="Vivo">Vivo</option>

</select>

 [/code]

In React, the selected value is defined with a value attribute on the select tag:

Example:

A simple select box, where the selected value "Iphone" is initialized in the constructor:

[code]

class MyForm extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      mbrand: ‘Iphone’

    };

  }

  render() {

    return (

      <form>

      <select value={this.state.mbrand}>

        <option value="Iphone">Iphone</option>

        <option value="Samsung">Samsung</option>

        <option value="Vivo">Vivo</option>

      </select>

      </form>

    );

  }

}

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

 [/code]

 These are the basic difference between normal HTML  and React Forms.

 To work and learn more on React visit www.skillbakery.com

 

No comments:

Post a Comment

Post Top Ad