Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Input value stucks in react.js

If, after rendering, you start entering text into the input, then everything is OK, but after clicking on the "fill" button and automatically filling in the fields, it is no longer possible to change their values

Please tell me where is the mistake

import React, {useState} from "react";

const Test = () => {

    const [item, setItem] = useState({});

    const updateItem = (e) => {

        item[e.target.id] = e.target.value;

        setItem(item);

    }

    const aaa = () => {

        let item = {
            link : 'testlink',
            title : 'testtitle',
            desc : 'testdesc'
        }

        setItem(item);

    }

    return (
        <form>
            <input type="text" name="link" id="link" value={item.link} onChange={updateItem} />
            <br/><br/>
            <input type="text" name="title" id="title" value={item.title} onChange={updateItem} />
            <br/><br/>
            <textarea          name="desc" id="desc" value={item.desc} onChange={updateItem} />
            <input type="button" value="click" onClick={aaa} />
        </form>
    );
}

export default Test;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I found some problem in your code and by fixing that I think your issue will be resolved :

First, you cannot assign value to state directly so change this part :

  const updateItem = (e) => {

        item[e.target.id] = e.target.value;

        setItem(item);

    }

to this part :

  const updateItem = (e) => {

        setItem({...item,[e.target.id]:e.target.value});

    }

Second, name of scope in aaa function is the same as state, that might cause error, so change name of it or assign value directly, like this :

   const aaa = () => {
        setItem({
            link : 'testlink',
            title : 'testtitle',
            desc : 'testdesc'
        });

    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading