Lesson 9 - Forms In React

9.1 - Creating Forms In React

Forms are the essential component of any web application. They allow you to collect user information for numerous purposes like authentication, sign up, verification, and so on.

Since React's JSX feature enables you to integrate HTML directly into JavaScript, designing the form is similar to HTML.

However, we may need to do some extra things such as creating a state to hold the form data.

Have a look at the following form,

import React, { useState } from 'react';

function App() {
 const [name, setName] = useState('');
 const [email, setEmail] = useState('');

 return (
 <form>
    <label>
        Name:
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
    </label>
    <br />
    <label>
        Email:
        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
    </label>
    <br />
    <button type="submit">Submit</button>
 </form>
 );
}

This form contains two input fields for name and email with a submit button. We also declared two states where the name state holds the name and the email state holds the email.

Think of this form as a preview, it doesn’t yet handle user input. But don’t worry, in our next lesson, we’ll dive into adding functionality to process the data.