How do I handle forms in React – Practical Approach

Practical Approach

This is a great and very interesting question. Handling forms in React can be a little challenging and can also be done by just creating a controlled component for the form and its input. Don’t worry here, let me take you through the practical procedures.

Consider the example below as an example of how to handle a simple form with two input fields namely:

  • the username
  • the password
……..in the controlled components:

1 class MyForm extends React.Component {

2    constructor(props) {

3        super(props);

4        this.state = {

5            username: ”,

6            password: ”,

7        };

8    }

9

10    handleUsernameChange = (event) => {

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

12   }

13

14    handlePasswordChange = (event) => {

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

16    }

17

18    handleSubmit = (event) => {

19        event.preventDefault();

20        // Handle form submission

21    }

22

23    render() {

24        return (

25            <form onSubmit={this.handleSubmit}>

26                <label>Username:</label>

27                <input type=”text” value={this.state.username} onChange={this.handleUsernameChange} />

28                <br />

29                <label>Password:</label>

30                <input type=”password” value={this.state.password} onChange={this.handlePasswordChange} />

31                <br />

32                <input type=”submit” value=”Submit” />

33            </form>

34        );

35    }

36 }

Related posts:

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading