Uncontrolled Textarea Element

ReactReactBeginner
Practice Now

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

Introduction

In this lab, we will learn how to create an uncontrolled <textarea> element in React. The purpose of this lab is to showcase how to use the defaultValue and onChange props to pass the value of the text area to a callback function in the parent component. By the end of this lab, you will have a better understanding of how to create uncontrolled input fields in React.


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-38365{{"`Uncontrolled Textarea Element`"}} end

Uncontrolled Textarea Element

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 function renders a <textarea> element that is not controlled by the parent component. It uses a callback function to pass the value of the input to the parent component.

To use this function:

  • Pass the defaultValue prop from the parent component as the initial value of the input field.
  • Use the onChange event to trigger the onValueChange callback and send the new value to the parent.
const TextArea = ({
  cols = 20,
  rows = 2,
  defaultValue,
  onValueChange,
  ...rest
}) => {
  return (
    <textarea
      cols={cols}
      rows={rows}
      defaultValue={defaultValue}
      onChange={({ target: { value } }) => onValueChange(value)}
      {...rest}
    />
  );
};

Example usage:

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

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 Textarea Element lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like