Uncontrolled Input Field

Beginner

This tutorial is from open-source community. Access the source code

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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Uncontrolled Input Field

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.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 defaultValue prop.
  • Pass a callback function called onValueChange to handle value updates.
  • Use the onChange event 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.