This content originally appeared on DEV Community and was authored by Joshua Evuetapha
Introduction
In HTML, if you want a textbox with some initial text you wrap text inside the textarea tag like this <textarea> Hello World </textarea>
, this is fully editable, but if you try this in react you will get an error. Trying to use the defaultValue
prop in react won't work either. if you add a value prop to the textarea the value of the text will be displayed but then it won't be editable, this is because the value
prop is immutable.
Solution
Passing a value
prop to textarea like this <textarea value={'Hello World'}> </textarea>
, will display the text Hello World on the textbox, but it won't be editable to make it editable we need to pass the a state to the value
prop and update that state with the onChange
prop like the code below.
import { useState } from 'react';
function TextBox () {
const [text, setText] = useState('Hello World');
return (
<textarea
value={text}
onChange={(e) => setText(e.target.value) }>
</textarea>
);
}
export default TextBox;
Inside the TextBox component, I initialize the text
state with 'Hello World' and passed it to the textarea as a value prop, this will be the initial text displayed in the text area. onChange={(e) => setText(e.target.value) }
this line of code updates the text
state, with the new value.
You can learn more about handling form in react here
This content originally appeared on DEV Community and was authored by Joshua Evuetapha

Joshua Evuetapha | Sciencx (2022-02-04T01:15:30+00:00) How to fix defaultValue error while working with textarea in React. Retrieved from https://www.scien.cx/2022/02/04/how-to-fix-defaultvalue-error-while-working-with-textarea-in-react/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.