HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

React Forms

React Forms

In React, handling forms involves capturing user input, managing the state of form components, and responding to user interactions.

Here's a basic guide on how to work with forms in React:

Controlled Components:

React recommends using controlled components for forms. In a controlled component, form data is handled by the state of a React component. Here's a simple example:

import React, { useState } from 'react';

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

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

const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission using formData
console.log(formData);
};

return (
<form onSubmit={handleSubmit}>
<label> Username: <input type="text" name="username" value={formData.username} onChange={handleChange} /> </label>
<label> Password: <input type="password" name="password" value={formData.password} onChange={handleChange} /> </label> <br />

<button type="submit">Submit</button>
</form>
);
};

export default MyForm;

In this example:

  • The 'formData' state holds the values of the form inputs.
  • The 'handleChange' function updates the state as the user types.
  • The form has an 'onSubmit' handler ('handleSubmit') that prevents the default form submission and logs the form data.