Introduction
In this lab, we will explore how to create an uncontrolled input field using React. An uncontrolled input field is a simple and flexible way to capture user input without managing the value state in the parent component. We will use a callback function to inform the parent about value updates, making it easy to integrate with other components and APIs.
Uncontrolled Input Field
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
This code renders an uncontrolled <input> element that uses a callback function to inform its parent about value updates. To use it:
- Pass the initial value down from the parent using the
defaultValueprop. - Pass a callback function called
onValueChangeto handle value updates. - Use the
onChangeevent to fire the callback and send the new value to the parent.
Here's an example:
const UncontrolledInput = ({ defaultValue, onValueChange, ...rest }) => {
return (
<input
defaultValue={defaultValue} target: { value } }) => onValueChange(value)}
{...rest}
/>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(
<UncontrolledInput
type="text"
placeholder="Insert some text here..."
/>
);
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 Uncontrolled Input Field lab. You can practice more labs in LabEx to improve your skills.