How can I update textarea
value in React? I used the setState
hook on a button to the textarea
‘s value
, but then I can’t edit the content of the textarea
, and when I use defaultValue
instead of value
or add an onChange
attribute to the textarea
, the setState
hook doesn’t work and the browser console throws me two warnings (which I will show below).
This is the warnings I get from the browser console, not sure why this happened. Also, if I only use setState
to the textarea
‘s value
, it works properly, but as mentioned before I cannot edit the content of the textarea
without changing the value
property to defaultValue
or add onChange
to the textarea
.
Edit:
The whole file’s code:
"use client";
import { Button } from "@mui/material";
import { useState } from "react";
export default function TextAreaCreate() {
const [content, setContent] = useState("<p></p><br/>")
function paragraph() {
setContent(content + "n<p></p>")
}
function handlechange(event: any) {
setContent(event.target.content)
}
return (
<div>
<textarea name="content" className="text-black border border-black w-full h-52" value={content} onChange={handlechange} required></textarea><br />
<div className="m-5">
<Button variant="contained" onClick={paragraph}>Paragraph</Button>
</div>
</div>
)
}
I’d share the code rather than console warnings. But here’s what I presume. You need to pass onChange
.
import React, { useState } from 'react';
function App() {
const [text, setText] = useState(''); // here's your state
const handleChange = (event) => {
setText(event.target.value); // you update the state as the user types
};
const updateText = () => {
setText('Updated Text'); // here you set a new value when a button is clicked
};
return (
<div>
<textarea
value={text} // Controlled component
onChange={handleChange} // you update state on change
/>
<button onClick={updateText}>Update Text</button>
</div>
);
}
export default App;
If you provide a value prop without onChange
, the textarea
becomes read-only, which is why you couldn’t edit the content.
1