React JS Forms

In this tutorial, we can see how the form works, how to capture the input value of the element

We can get more ideas by looking below the example. Which have a textbox, a textarea, and a dropdown. you can put this file in /src/components folder and put in /src/App.js file.

1. FormComponent

FormComponent
import React, { Component } from 'react'; class FormComponent extends Component { constructor(props) { super(props) this.state = { salutation : '', firstName: '', address:'' } } handleFirstNameChange = (event) => { this.setState({ firstName : event.target.value }); } handleAddressChange = (event) => { this.setState({ address : event.target.value }); } handleSalutationChange = (event) => { this.setState({ salutation : event.target.value }); } handleSubmit = (event) => { alert(`Hi, ${this.state.salutation} ${this.state.firstname} is living at ${this.state.address}.`) } render() { return( <form onSubmit={this.handleSubmit}> <div> <label>Salutation</label> <Select value={this.state.salutation} onChange={this.handleSalutationChange}> <Option value="Mr">Mr</Option> <Option value="Mrs">Mrs</Option> <Option value="Ms">Ms</Option> </Select> </div> <div> <label>First Name</label> <input type='text' value={this.state.firstname} onChange={this.handleFirstNameChange} > </div> <div> <label>Address</label> <input type='textarea' value={this.state.address} onChange={this.handleAddressChange} > </div> <button type='submit'>Submit</button> </form> ); } } export default FormComponent;

Above code shows one select list having a value of Mr, Mrs, Ms in it. one textbox of firstName and one textarea of address. when we click on submit button after filling value, it will alert filled data in browser. Here we have one state to save input value and one event handler for each field. we can also take {this.handleSubmit} at onClick of submit button. which gives the same output.

 

← Previous

Next →