Introduction
This article covers the following tech skills:
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.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.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 defaultValueprop from the parent component as the initial value of the input field.
- Use the onChangeevent to trigger theonValueChangecallback 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.
π Practice Now: Uncontrolled Textarea Element
Want to Learn More?
- π³ Learn the latest React Skill Trees
- π Read More React Tutorials
- π¬ Join our Discord or tweet us @WeAreLabEx
 

 
                      
 
    
Top comments (0)