I'm making a web app with react and in one of my functions I fetch some data from the backend and then I show it to the user by changing the value of the textarea. The problem is that I want the textarea not to be edited when the user presses a button to fetch the data from the backend but then if I click the textarea I want it to erease the data fetched and allow the user to write into itself.
This is how the code looks like in the component that contains the textarea:
<div id="text-div" onClick={this.onWrite}>
<textarea id="text" rows={13} value={this.state.value} onChange={this.handleChange}></textarea></div>
<Button onClick={this.handleRead}>Read</Button>
//functions within the code
onWrite() {
// do stuff
document.getElementById("text").setAttribute("contentEditable", true);
}
async handleRead() {
// fetches data and saves it into this.state.value
document.getElementById("text").setAttribute("contentEditable", false);
}
I've also tried using readOnly
but it doesn't work either, when I call handleRead()
it doesnt let the user write and shows the data (as expected) but when i call onWrite()
(it would set readOnly property to false) it does not let the user write. So I cant revert what handleRead()
did.
I would really appreciate some suggestions because I'm kind of a noob in React and this is my first project, sorry if I missed something.
CodePudding user response:
contenteditable
is an attribute added to non-editable fields like div
to make them editable
You want to use readonly
or disabled
I converted your example to vanilla to make it usable here
function onWrite() {
// do stuff
document.getElementById("text").removeAttribute("readonly");
}
async function handleRead() {
document.getElementById("text").value = 'test'
document.getElementById("text").setAttribute("readonly", true)
}
<div id="text-div" onclick="onWrite()">
<textarea id="text" rows="13"></textarea>
</div>
<button onclick="handleRead()">Read</button>
CodePudding user response:
This might be because you have already assigned some value to your input field.
So use defaultValue
instead of value
So try writing your code like this
<div id="text-div" onClick={this.onWrite}> <textarea id="text" rows={13} defaultValue={this.state.value} onChange={this.handleChange}></textarea></div> <Button onClick={this.handleRead}>Read</Button>
This should solve your problem.