Building Interactive Forms in React: A Practical Tutorial with code example

Forms play a critical role in web development, enabling users to input and submit data to the server. In this article, we’ll explore how to handle forms in React.js using controlled components, managing form state, validation, and form submissions. By the end of this tutorial, you’ll be equipped with the knowledge to build robust and interactive forms in your React applications.

Prerequisites:

Before proceeding, ensure you have Node.js and npm (Node Package Manager) installed on your system. Familiarity with React.js and basic HTML form concepts is recommended.

Step 1: Setting Up the Project

To get started, create a new React.js project using Create React App. Open your terminal and run the following command:

npx create-react-app react-forms-demo
cd react-forms-demo

Step 2: Create the Form Component

In this example, we’ll create a simple login form with an email and password input. When the form is submitted, we’ll display the entered email and password in the console.

Create a new file named LoginForm.js inside the src folder:

// src/LoginForm.js

import React, { useState } from 'react';

const LoginForm = () => {
  const [formData, setFormData] = useState({
    email: '',
    password: '',
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Submitted Form Data:', formData);
    // Add form submission logic here (e.g., send data to the server)
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
          required
        />
      </div>
      <div>
        <label htmlFor="password">Password:</label>
        <input
          type="password"
          id="password"
          name="password"
          value={formData.password}
          onChange={handleChange}
          required
        />
      </div>
      <button type="submit">Login</button>
    </form>
  );
};

export default LoginForm;

Step 3: Implement the Form

Modify src/App.js to render the LoginForm component:

// src/App.js

import React from 'react';
import LoginForm from './LoginForm';

function App() {
  return (
    <div>
      <h1>React Forms Handling Example</h1>
      <LoginForm />
    </div>
  );
}

export default App;

Step 4: Testing the Application

Run the development server:

codenpm start

Visit http://localhost:3000 in your browser to see the login form. Enter an email and password, then click the “Login” button. You should see the submitted form data printed in the console.

Conclusion:

In this tutorial, we learned how to handle forms in React.js using controlled components. We created a simple login form, managed form state with the useState hook, and handled form submission with the handleSubmit function. Additionally, we learned about the onChange event to track user input and update the form data accordingly.

With this foundation, you can now build more complex forms, perform form validation, and handle form submissions with ease. React’s declarative nature and controlled component approach make it powerful for managing forms and providing a seamless user experience.

Leave a Comment

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

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top