telpel225
telpel225

Reputation: 15

How do I clear the textarea's value when clicked on the addbtn in reactjs?

I used the following code, but the text does not clear when I click the addbtn. This is a reactjs project.

function Addpage() {

    const[note, setnote] = useState("");
    function textchange(e) {
        setnote(e.target.value);
        console.log(note);
    };
    
        function savenote(){
        localStorage.setItem('savednotes', note);
        setnote("");
    };

    return (
        <>
        <Headersmall/>
        <br/>
        <div className="addcard">
            <h1>Add new note.</h1>
            <div className="title">
                <input type="text" className="titlebox" id="addtitle" placeholder="Title"/>
            </div>
            <br/>
            <div className="note">
                <textarea type="text" className="notebox" id="addtxt" placeholder="Note" onChange = {textchange}/>
            </div>
            <br/>
            <button className="addbtn" id='addbtn' onClick = {savenote}>Save</button>
        </div>
        <br/>
        </>
    )
}

Upvotes: 1

Views: 45

Answers (1)

Areeb Khan
Areeb Khan

Reputation: 413

When you're setting the value of note as an empty string by doing setnote("") inside savenote() function, you ARE changing the value of the state variable note, but it doesn't reflect in the textarea because your textarea input doesn't have a value associated to it. Try adding value={note} which will mean that there will be a "set and fetch" relationship between the textarea and the 'note' state variable

<textarea
 value={note}
 type="text"
 className="notebox"
 id="addtxt"
 placeholder="Note"
 onChange={textchange}
>

Upvotes: 1

Related Questions