DEV Community

Cover image for Uncontrolled Textarea Element in React
Labby for LabEx

Posted on

Uncontrolled Textarea Element in React

Introduction

This article covers the following tech skills:

Skills Graph

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.

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}
    />
  );
};
Enter fullscreen mode Exit fullscreen mode

Example usage:

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

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.

MindMap


πŸš€ Practice Now: Uncontrolled Textarea Element


Want to Learn More?

Top comments (0)