React controlled components

Created By: chatGPT

In React, a controlled component is a component that does not maintain its own state. Instead, it gets its current value from props and notifies changes via an event handler. This is particularly useful for managing forms, where you want to control the input values programmatically and maintain a single source of truth for the component's state.
const ControlledInput = () => {
    const [value, setValue] = useState('');

    const handleChange = (e) => {
        setValue(e.target.value);
    };

    return (
        <input
            type="text"
            value={value}
            onChange={handleChange}
        />
    );
};
To use controlled components effectively, make sure that the input elements have their value attribute bound to the state variable. This way, any input by the user will set the state, allowing you to manage the value of the input seamlessly.
const ControlledForm = () => {
    const [inputValue, setInputValue] = useState('');

    const handleInputChange = (event) => {
        setInputValue(event.target.value);
    };

    const handleSubmit = (event) => {
        event.preventDefault();
        console.log('Submitted Value:', inputValue);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                value={inputValue}
                onChange={handleInputChange}
            />
            <button type="submit">Submit</button>
        </form>
    );
};
For better user experience, you can also implement features like validation within controlled components. For example, you can check if the input meets certain criteria and display error messages as necessary.
const ValidatedInput = () => {
    const [value, setValue] = useState('');
    const [error, setError] = useState('');

    const handleChange = (e) => {
        const newValue = e.target.value;
        setValue(newValue);
        setError(newValue.length < 5 ? 'Input must be at least 5 characters.' : '');
    };

    return (
        <div>
            <input
                type="text"
                value={value}
                onChange={handleChange}
            />
            {error && <p style={{ color: 'red' }}>{error}</p>}
        </div>
    );
};
To recap, using controlled components in React allows for greater flexibility and control over the form elements. By relying on state and event handlers, you can create dynamic forms that react to user input and update efficiently. This approach enhances code maintainability and makes debugging easier.
import React, { useState } from 'react';

const App = () => {
    return (
        <div>
            <ControlledInput />
            <ControlledForm />
            <ValidatedInput />
        </div>
    );
};

export default App;
Introduction And SetupComponentsPropsStateLifecycle MethodsHooksContext APIJsx SyntaxVirtual DomEvent HandlingFormsRoutingPerformance OptimizationError BoundariesHigher Order ComponentsRender PropsPortalsFragmentsRefsControlled ComponentsUncontrolled ComponentsMemoizationSuspenseLazy LoadingProp TypesDefault PropsConditional RenderingList And KeysAccessibility (a11y)State ManagementTestingCustom HooksUseEffectUseStateUseContextUseReducerUseMemoUseCallbackUseRefUseLayoutEffectUseImperativeHandleUseDebugValueAutomatic BatchingSuspense For Data FetchingStrict ModeForward RefsCreateContextLazyUseTransitionUseDeferredValueUseId