Question:
Fix textarea typing not working issue when state is set through object

If you are facing issues with textarea typing not working when the state is set through an object in React, it's important to ensure that you are updating the state correctly and handling the event properly. 


Here we are showing 2 codes. The first one is for the condition when the “state is set with direct variable” and the second code is for the condition “when the state is set through object.”


Code 1 (state is set with direct variable)

const [description, setDescription] = useState('');


<label>Test suite description</label>

<textarea value={description} name="description" 

    rows={4} cols={5}  style={{width: "100%"}}

    onChange={(e) => setDescription(e.target.value)}>                                      

</textarea>


Case 2 state is set through object )

  const [tsData, setTsData] = useState({

    tsname: "",

    description: "",

    plugin: 100,

    type: 900,

    freq: 100,

    report: 0,

  });

  

  const handleTextAreaType=(value)=> {

    const newTsData = {...tsData};

    newTsData.description = value;

    setTsData(newTsData);

  }



<label>Test suite description</label>

<textarea value={description} name="description" 

    rows={4} cols={5}  style={{width: "100%"}} 

    onChange={(e) => handleTextAreaType(e.target.value)}>                                      

</textarea> 


Remember in react, you can't directly mutate the state. Instead you need to create a new object everytime.


So instead of doing const newTsData = tsData;, you have to do const newTsData = {...tsData};


This will create a new object with a different reference, and hence react will know that state has changed and it will then re-render. If you directly copy the state to a new variable, the reference is still the same (since it is an object) and hence react would think that state is still the same and hence it would not re-render


Answered by: >ALTHAF PJALEEL

Credit:> Stack Overflow


Suggested blogs:

>How .transform handle the splitted groups?

>Can I use VS Code's launch config to run a specific python file?

>Python: How to implement plain text to HTML converter?

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks

>How to replace a value by another in certain columns of a 3d Numpy array?

>How to fix "segmentation fault" issue when using PyOpenGL on Mac?


Submit
0 Answers