DEV Community

Joshua Evuetapha
Joshua Evuetapha

Posted on

 

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

Top comments (0)

The JavaScript Brief

1. Top 5 MERN STACK projects to improve your practical understanding

Boost your MERN Stack development skills by undertaking interesting beginner projects. These five engaging projects cover web applications and range from social media website applications to geo-social networking maps. Hone your understanding and apply modern techniques backed up by hands-on experience.

2. How To Optimize Your React App’s Performance

Learn the best optimizing techniques to make your React applications faster and more efficient. Focusing on the identification of performance bottlenecks and common pitfalls to avoid, these optimization strategies will keep your applications running smoothly even when faced with growing complexity.

3. A story of let, const, object mutation, and a bug in my code

In the pursuit of bug-free code, explore an incident involving a mix-up between const and let, making sure your custom code works effectively with third

party documentation. Discover best practices on program flow and learn about JavaScript's unpredictable aspects to ensure your core code is robust.