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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay