Skip to content

Home

Controlled input field

Renders a controlled <input> element that uses a callback function to inform its parent about value updates.

const ControlledInput = ({ value, onValueChange, ...rest }) => {
  return (
    <input
      value={value}
      onChange={({ target: { value } }) => onValueChange(value)}
      {...rest}
    />
  );
};

const Form = () => {
  const [value, setValue] = React.useState('');

  return (
    <ControlledInput
      type="text"
      placeholder="Insert some text here..."
      value={value}
      onValueChange={setValue}
    />
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <Form />
);

More like this

Start typing a keyphrase to see matching snippets.