DEV Community

Joshua Evuetapha
Joshua Evuetapha

Posted on

3 2

How to fix defaultValue error while working with textarea in React

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;

Enter fullscreen mode Exit fullscreen mode

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay