Controlled input changing on setState()How to create a controlled input with empty default in React 15React - changing an uncontrolled inputEditdamnpoll is changing an uncontrolled input of type text to be controlledReact form error changing a controlled input of type text to be uncontrolledReact warning: “is changing an uncontrolled input of type hidden to be controlled” why?Input elements should not switch from controlled to uncontrolled ReactJs errorReact - Change a JSON Object in setStateWarning when changing controlled input value in ReactIs this error Important? Component uncontrolled to controlledWhy I'm thrown the Warning: A component is changing an uncontrolled input of type text to be controlled

How did the Super Star Destroyer Executor get destroyed exactly?

How can saying a song's name be a copyright violation?

Why is consensus so controversial in Britain?

How can I determine if the org that I'm currently connected to is a scratch org?

Is there a hemisphere-neutral way of specifying a season?

What are some good books on Machine Learning and AI like Krugman, Wells and Graddy's "Essentials of Economics"

Expand and Contract

Could the museum Saturn V's be refitted for one more flight?

Can we compute the area of a quadrilateral with one right angle when we only know the lengths of any three sides?

Forgetting the musical notes while performing in concert

A category-like structure without composition?

Reverse dictionary where values are lists

How do I handle a potential work/personal life conflict as the manager of one of my friends?

CAST throwing error when run in stored procedure but not when run as raw query

Plagiarism or not?

What killed these X2 caps?

Can compressed videos be decoded back to their uncompresed original format?

Should I tell management that I intend to leave due to bad software development practices?

What method can I use to design a dungeon difficult enough that the PCs can't make it through without killing them?

Why do bosons tend to occupy the same state?

How to Recreate this in LaTeX? (Unsure What the Notation is Called)

How could indestructible materials be used in power generation?

Bullying boss launched a smear campaign and made me unemployable

Short story with a alien planet, government officials must wear exploding medallions



Controlled input changing on setState()


How to create a controlled input with empty default in React 15React - changing an uncontrolled inputEditdamnpoll is changing an uncontrolled input of type text to be controlledReact form error changing a controlled input of type text to be uncontrolledReact warning: “is changing an uncontrolled input of type hidden to be controlled” why?Input elements should not switch from controlled to uncontrolled ReactJs errorReact - Change a JSON Object in setStateWarning when changing controlled input value in ReactIs this error Important? Component uncontrolled to controlledWhy I'm thrown the Warning: A component is changing an uncontrolled input of type text to be controlled













0















I have this constructor in React component:



constructor() {

super();

this.state =
info:
title: '',
description: '',
height: ''



...


And a form with inputs controlled by the state:



 <form onSubmit=this.handleFormSubmit>
<label>Title:</label>
<input type="text" name="title" value=this.state.info.title onChange=(e) => this.handleChange(e) />
<label>Description:</label>
<input type="text" name="description" value=this.state.info.description onChange=(e) => this.handleChange(e) />
...


When I type anything on the form, I guess there's something wrong with my handler, as I get the warning "Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component."



Checking console, it seems state is updating each property value that is being typed, and removing other properties, while it should remain all of them and only update the changed ones.



Here's my handler:



handleChange(event) 
let name, value = event.target;
this.setState(
info:
[name]: value

);










share|improve this question


























    0















    I have this constructor in React component:



    constructor() {

    super();

    this.state =
    info:
    title: '',
    description: '',
    height: ''



    ...


    And a form with inputs controlled by the state:



     <form onSubmit=this.handleFormSubmit>
    <label>Title:</label>
    <input type="text" name="title" value=this.state.info.title onChange=(e) => this.handleChange(e) />
    <label>Description:</label>
    <input type="text" name="description" value=this.state.info.description onChange=(e) => this.handleChange(e) />
    ...


    When I type anything on the form, I guess there's something wrong with my handler, as I get the warning "Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component."



    Checking console, it seems state is updating each property value that is being typed, and removing other properties, while it should remain all of them and only update the changed ones.



    Here's my handler:



    handleChange(event) 
    let name, value = event.target;
    this.setState(
    info:
    [name]: value

    );










    share|improve this question
























      0












      0








      0








      I have this constructor in React component:



      constructor() {

      super();

      this.state =
      info:
      title: '',
      description: '',
      height: ''



      ...


      And a form with inputs controlled by the state:



       <form onSubmit=this.handleFormSubmit>
      <label>Title:</label>
      <input type="text" name="title" value=this.state.info.title onChange=(e) => this.handleChange(e) />
      <label>Description:</label>
      <input type="text" name="description" value=this.state.info.description onChange=(e) => this.handleChange(e) />
      ...


      When I type anything on the form, I guess there's something wrong with my handler, as I get the warning "Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component."



      Checking console, it seems state is updating each property value that is being typed, and removing other properties, while it should remain all of them and only update the changed ones.



      Here's my handler:



      handleChange(event) 
      let name, value = event.target;
      this.setState(
      info:
      [name]: value

      );










      share|improve this question














      I have this constructor in React component:



      constructor() {

      super();

      this.state =
      info:
      title: '',
      description: '',
      height: ''



      ...


      And a form with inputs controlled by the state:



       <form onSubmit=this.handleFormSubmit>
      <label>Title:</label>
      <input type="text" name="title" value=this.state.info.title onChange=(e) => this.handleChange(e) />
      <label>Description:</label>
      <input type="text" name="description" value=this.state.info.description onChange=(e) => this.handleChange(e) />
      ...


      When I type anything on the form, I guess there's something wrong with my handler, as I get the warning "Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component."



      Checking console, it seems state is updating each property value that is being typed, and removing other properties, while it should remain all of them and only update the changed ones.



      Here's my handler:



      handleChange(event) 
      let name, value = event.target;
      this.setState(
      info:
      [name]: value

      );







      reactjs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 21 at 21:16









      BiomehanikaBiomehanika

      796829




      796829






















          3 Answers
          3






          active

          oldest

          votes


















          3














          the one you are using is updating only one props and the others being stripped that causes React shows warning. you can use spreading to keep the others



          handleChange(event) 
          let name, value = event.target;
          this.setState(
          info:
          ...this.state.info,
          [name]: value

          );






          share|improve this answer

























          • THANK YOU. I'll tick in some minutes.

            – Biomehanika
            Mar 21 at 21:29











          • you may want to use the function version of set state in this case, so you don't end up with stale values...

            – Garrett Motzner
            Mar 21 at 21:30


















          1














          There's usually 2 cases which cause such warnings to manifest in my experience.



          1. The initial value of the property in state is undefined and not being changed when updated

          2. The initial value is '' and being changed to null





          share|improve this answer






























            1














            Try this:



            handleChange(event) 
            let name, value = event.target;
            this.setState((info) =>(
            info:
            [name]: value

            ));



            Breaking down the function call:



            • First you have this.setState(updaterFunction). updaterFunction gets called by setState with the previous state as the argument, and that function is expected to return an object with the keys of the state to update (it gets merged shallowly with the previous state).

            • Because setState is only a shallow merge (no matter if you pass it an object or a function), if you have an object at like this.state.foo.bar and you update the state with an object like foo: bar: 'qux' , the old foo will not get merged with the new foo, it will instead get replaced. So your updater function needs to do the deeper merging manually.

            • The updaterFunction looks like this (info)=>(…). We pull info out of the previous state, and we return an object, using info to manually do the deeper merging.

            The benefit of passing a function to setState (instead of just an object) is that if you use the state passed to the function instead of this.state, you will avoid some potential bugs when multiple setState calls get batched together....






            share|improve this answer

























            • Thank you Garret, also great alternative

              – Biomehanika
              Mar 22 at 6:54











            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55289374%2fcontrolled-input-changing-on-setstate%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            the one you are using is updating only one props and the others being stripped that causes React shows warning. you can use spreading to keep the others



            handleChange(event) 
            let name, value = event.target;
            this.setState(
            info:
            ...this.state.info,
            [name]: value

            );






            share|improve this answer

























            • THANK YOU. I'll tick in some minutes.

              – Biomehanika
              Mar 21 at 21:29











            • you may want to use the function version of set state in this case, so you don't end up with stale values...

              – Garrett Motzner
              Mar 21 at 21:30















            3














            the one you are using is updating only one props and the others being stripped that causes React shows warning. you can use spreading to keep the others



            handleChange(event) 
            let name, value = event.target;
            this.setState(
            info:
            ...this.state.info,
            [name]: value

            );






            share|improve this answer

























            • THANK YOU. I'll tick in some minutes.

              – Biomehanika
              Mar 21 at 21:29











            • you may want to use the function version of set state in this case, so you don't end up with stale values...

              – Garrett Motzner
              Mar 21 at 21:30













            3












            3








            3







            the one you are using is updating only one props and the others being stripped that causes React shows warning. you can use spreading to keep the others



            handleChange(event) 
            let name, value = event.target;
            this.setState(
            info:
            ...this.state.info,
            [name]: value

            );






            share|improve this answer















            the one you are using is updating only one props and the others being stripped that causes React shows warning. you can use spreading to keep the others



            handleChange(event) 
            let name, value = event.target;
            this.setState(
            info:
            ...this.state.info,
            [name]: value

            );







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 21 at 22:26

























            answered Mar 21 at 21:27









            duc maiduc mai

            38336




            38336












            • THANK YOU. I'll tick in some minutes.

              – Biomehanika
              Mar 21 at 21:29











            • you may want to use the function version of set state in this case, so you don't end up with stale values...

              – Garrett Motzner
              Mar 21 at 21:30

















            • THANK YOU. I'll tick in some minutes.

              – Biomehanika
              Mar 21 at 21:29











            • you may want to use the function version of set state in this case, so you don't end up with stale values...

              – Garrett Motzner
              Mar 21 at 21:30
















            THANK YOU. I'll tick in some minutes.

            – Biomehanika
            Mar 21 at 21:29





            THANK YOU. I'll tick in some minutes.

            – Biomehanika
            Mar 21 at 21:29













            you may want to use the function version of set state in this case, so you don't end up with stale values...

            – Garrett Motzner
            Mar 21 at 21:30





            you may want to use the function version of set state in this case, so you don't end up with stale values...

            – Garrett Motzner
            Mar 21 at 21:30













            1














            There's usually 2 cases which cause such warnings to manifest in my experience.



            1. The initial value of the property in state is undefined and not being changed when updated

            2. The initial value is '' and being changed to null





            share|improve this answer



























              1














              There's usually 2 cases which cause such warnings to manifest in my experience.



              1. The initial value of the property in state is undefined and not being changed when updated

              2. The initial value is '' and being changed to null





              share|improve this answer

























                1












                1








                1







                There's usually 2 cases which cause such warnings to manifest in my experience.



                1. The initial value of the property in state is undefined and not being changed when updated

                2. The initial value is '' and being changed to null





                share|improve this answer













                There's usually 2 cases which cause such warnings to manifest in my experience.



                1. The initial value of the property in state is undefined and not being changed when updated

                2. The initial value is '' and being changed to null






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 21 at 21:26









                ThatCoderGuyThatCoderGuy

                42226




                42226





















                    1














                    Try this:



                    handleChange(event) 
                    let name, value = event.target;
                    this.setState((info) =>(
                    info:
                    [name]: value

                    ));



                    Breaking down the function call:



                    • First you have this.setState(updaterFunction). updaterFunction gets called by setState with the previous state as the argument, and that function is expected to return an object with the keys of the state to update (it gets merged shallowly with the previous state).

                    • Because setState is only a shallow merge (no matter if you pass it an object or a function), if you have an object at like this.state.foo.bar and you update the state with an object like foo: bar: 'qux' , the old foo will not get merged with the new foo, it will instead get replaced. So your updater function needs to do the deeper merging manually.

                    • The updaterFunction looks like this (info)=>(…). We pull info out of the previous state, and we return an object, using info to manually do the deeper merging.

                    The benefit of passing a function to setState (instead of just an object) is that if you use the state passed to the function instead of this.state, you will avoid some potential bugs when multiple setState calls get batched together....






                    share|improve this answer

























                    • Thank you Garret, also great alternative

                      – Biomehanika
                      Mar 22 at 6:54















                    1














                    Try this:



                    handleChange(event) 
                    let name, value = event.target;
                    this.setState((info) =>(
                    info:
                    [name]: value

                    ));



                    Breaking down the function call:



                    • First you have this.setState(updaterFunction). updaterFunction gets called by setState with the previous state as the argument, and that function is expected to return an object with the keys of the state to update (it gets merged shallowly with the previous state).

                    • Because setState is only a shallow merge (no matter if you pass it an object or a function), if you have an object at like this.state.foo.bar and you update the state with an object like foo: bar: 'qux' , the old foo will not get merged with the new foo, it will instead get replaced. So your updater function needs to do the deeper merging manually.

                    • The updaterFunction looks like this (info)=>(…). We pull info out of the previous state, and we return an object, using info to manually do the deeper merging.

                    The benefit of passing a function to setState (instead of just an object) is that if you use the state passed to the function instead of this.state, you will avoid some potential bugs when multiple setState calls get batched together....






                    share|improve this answer

























                    • Thank you Garret, also great alternative

                      – Biomehanika
                      Mar 22 at 6:54













                    1












                    1








                    1







                    Try this:



                    handleChange(event) 
                    let name, value = event.target;
                    this.setState((info) =>(
                    info:
                    [name]: value

                    ));



                    Breaking down the function call:



                    • First you have this.setState(updaterFunction). updaterFunction gets called by setState with the previous state as the argument, and that function is expected to return an object with the keys of the state to update (it gets merged shallowly with the previous state).

                    • Because setState is only a shallow merge (no matter if you pass it an object or a function), if you have an object at like this.state.foo.bar and you update the state with an object like foo: bar: 'qux' , the old foo will not get merged with the new foo, it will instead get replaced. So your updater function needs to do the deeper merging manually.

                    • The updaterFunction looks like this (info)=>(…). We pull info out of the previous state, and we return an object, using info to manually do the deeper merging.

                    The benefit of passing a function to setState (instead of just an object) is that if you use the state passed to the function instead of this.state, you will avoid some potential bugs when multiple setState calls get batched together....






                    share|improve this answer















                    Try this:



                    handleChange(event) 
                    let name, value = event.target;
                    this.setState((info) =>(
                    info:
                    [name]: value

                    ));



                    Breaking down the function call:



                    • First you have this.setState(updaterFunction). updaterFunction gets called by setState with the previous state as the argument, and that function is expected to return an object with the keys of the state to update (it gets merged shallowly with the previous state).

                    • Because setState is only a shallow merge (no matter if you pass it an object or a function), if you have an object at like this.state.foo.bar and you update the state with an object like foo: bar: 'qux' , the old foo will not get merged with the new foo, it will instead get replaced. So your updater function needs to do the deeper merging manually.

                    • The updaterFunction looks like this (info)=>(…). We pull info out of the previous state, and we return an object, using info to manually do the deeper merging.

                    The benefit of passing a function to setState (instead of just an object) is that if you use the state passed to the function instead of this.state, you will avoid some potential bugs when multiple setState calls get batched together....







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 21 at 21:45

























                    answered Mar 21 at 21:33









                    Garrett MotznerGarrett Motzner

                    823315




                    823315












                    • Thank you Garret, also great alternative

                      – Biomehanika
                      Mar 22 at 6:54

















                    • Thank you Garret, also great alternative

                      – Biomehanika
                      Mar 22 at 6:54
















                    Thank you Garret, also great alternative

                    – Biomehanika
                    Mar 22 at 6:54





                    Thank you Garret, also great alternative

                    – Biomehanika
                    Mar 22 at 6:54

















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55289374%2fcontrolled-input-changing-on-setstate%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                    Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?