Mark As Completed Discussion

Creating a Basic Form

To build a basic form with input fields in React, we can make use of the form element and various form input elements such as input, select, textarea, etc.

Let's start by creating a simple form component called BasicForm that consists of two input fields: Name and Email.

SNIPPET
1import React, { useState } from 'react';
2
3const BasicForm = () => {
4  const [name, setName] = useState('');
5  const [email, setEmail] = useState('');
6
7  const handleSubmit = (e) => {
8    e.preventDefault();
9    // Perform form validation and submission logic here
10  }
11
12  return (
13    <div>
14      <h2>Basic Form</h2>
15      <form onSubmit={handleSubmit}>
16        <label htmlFor='name'>Name:</label>
17        <input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
18
19        <label htmlFor='email'>Email:</label>
20        <input type='email' id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
21
22        <button type='submit'>Submit</button>
23      </form>
24    </div>
25  );
26}
27
28export default BasicForm;

In the code above, we import the necessary dependencies and define the BasicForm component. Inside the component, we initialize state variables name and email using the useState hook.

The form has an onSubmit event listener that calls the handleSubmit function when the form is submitted. In this function, you can perform any form validation or submission logic.

Each input field has a corresponding state variable (name and email) and an onChange event listener that updates the state when the user enters input.

Try implementing the BasicForm component and see how it renders a basic form with input fields for Name and Email!

TSX
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment