The most common way to create a React component is to make it controlled. This means that the component is controlled by the parent component. The parent component is responsible for passing the value to the component and handling the change event. A common example of a controlled component is a text input.
However, there are times when you want to create a component that can be controlled and uncontrolled. This is useful when you want to provide a default value for a component but also allow the user to change it.
function Checkbox(props) { return <input type="checkbox" checked={props.checked} onChange={props.onChange} />; }
In this post, we'll look at how to create a component that can be controlled and uncontrolled. We'll also look at how to create a component that can be controlled and uncontrolled with a default value.
We'll create a component that can be controlled and uncontrolled with a default value. The component will be a text input.
function MyInput() { const [value, setValue] = useState(''); return <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />; }
function MyInput(props) { return <input type="text" value={props.value} onChange={props.onChange} />; }
So far, we've created a controlled and uncontrolled component. As you can see, the controlled component is very similar to the uncontrolled component. The only difference is that the controlled component takes the value and onChange props.
The sauce is in the props. You should provide an optional values for the value and onChange props. If the value prop is not provided, the component should use the internal state. If the onChange prop is not provided, the component should not handle the change event.
function MyInput(props) { const isControlled = props.value !== undefined; const [value, setValue] = useState(''); return ( <input type="text" value={isControlled ? props.value : value} onChange={isControlled ? props.onChange : (e) => setValue(e.target.value)} /> ); } MyInput.defaultProps = { value: undefined, onChange: undefined, };