Skip to main content

Form Types in React (Live Playground)

Forms are a vital part of any web application, and understanding different form types in React is crucial for managing user input effectively. In this tutorial, we'll explore different form types in React, including controlled and uncontrolled components, with sample code and simple explanations.

Controlled Components

Controlled components are form elements that have their state managed by React. In controlled components, the state is updated in response to user input, and the updated state is then used to set the value of the input field.

Here's an example of a controlled input component:

JavaScript
import React, { useState } from 'react';

function ControlledForm() {
const [name, setName] = useState('');

const handleChange = event => {
setName(event.target.value);
};

const handleSubmit = event => {
event.preventDefault();
console.log(`Form submitted with: ${name}`);
};

return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}

export default ControlledForm;

In this example, the input's value is controlled by the name state variable, which is updated through the handleChange function.

Live Playground, Try it Yourself

Uncontrolled Components

Uncontrolled components are form elements that have their state managed by the DOM itself. In uncontrolled components, you can use a ref to access the value of the input field directly.

Here's an example of an uncontrolled input component:

JavaScript
import React, { useRef } from 'react';

function UncontrolledForm() {
const inputRef = useRef();

const handleSubmit = event => {
event.preventDefault();
console.log(`Form submitted with: ${inputRef.current.value}`);
};

return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
}

export default UncontrolledForm;

In this example, the input's value is not controlled by React state, but instead, it's accessed directly using the inputRef when the form is submitted.

Live Playground, Try it Yourself

Choosing Between Controlled and Uncontrolled Components

Both controlled and uncontrolled components have their use cases. Controlled components are generally recommended for most situations, as they provide better control over form data and easier integration with React's state management.

Uncontrolled components can be useful when dealing with form elements that don't require validation or when interacting with non-React libraries that require direct access to the DOM.

Conclusion

Understanding different form types in React is essential for building effective and dynamic user interfaces. By learning about controlled and uncontrolled components, you'll be better equipped to handle user input in your React applications. With a solid grasp of form types in React, you'll be well on your way to becoming an effective React developer.