generated form in react in javascript

To create a form in React, we need to use JSX and a combination of React components. Here's an example:

index.tsx
import React, { useState } from 'react';

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

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(`Name: ${name}, Email: ${email}`);
  };

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

In this example, we are creating a component called Form. Inside the component, we are using the useState hook to manage the state of the form fields (name and email). We are also defining a handleSubmit function that logs the values of the form fields when the form is submitted.

In the return statement, we are rendering a form element with two label elements and two input elements. We are using the value prop to set the initial values of the form fields, and the onChange prop to update the state of the fields as the user types. Finally, we are rendering a button element with a type of submit, which will trigger the handleSubmit function when clicked.

This is just a basic example, but you can customize the form by adding more fields or styling it with CSS.

related categories

gistlibby LogSnag