Introduction
In this lab, we will learn how to create a controlled input field in React. The controlled input field is a common pattern used to manage form input values in React applications. By using a callback function to inform the parent component of any value updates, we can ensure that the input field's value is always in sync with the state of the parent component. This lab will guide us through the creation and usage of a controlled input field component in React.
Controlled Input Field
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
This code snippet provides a controlled <input> element that utilizes a callback function to inform its parent about any updates to its value. Here's how it works:
- The controlled input field's value is determined by the
valueprop passed down from the parent. - Any changes made to the input field by the user are captured by the
onChangeevent, which triggers theonValueChangecallback function and sends the new value back up to the parent component. - To update the input field's value, the parent must update the
valueprop that it passes down to the controlled input component.
Here's an example implementation of the ControlledInput component, followed by a usage example in a Form component:
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 />);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the Controlled Input Field lab. You can practice more labs in LabEx to improve your skills.