Uncontrolled Input Field

ReactReactBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") subgraph Lab Skills react/event_handling -.-> lab-38369{{"`Uncontrolled Input Field`"}} end

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}
      onChange={({ target: { value } }) => onValueChange(value)}
      {...rest}
    />
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(
  <UncontrolledInput
    type="text"
    placeholder="Insert some text here..."
    onValueChange={console.log}
  />
);

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.

Other React Tutorials you may like