How to change checkbox in react correctly?How do JavaScript closures work?How do I check if an element is hidden in jQuery?How to change an element's class with JavaScript?How do I remove a property from a JavaScript object?Setting “checked” for a checkbox with jQuery?How do I redirect to another webpage?How do I correctly clone a JavaScript object?How to check whether a checkbox is checked in jQuery?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

Using "Kollege" as "university friend"?

Are glider winch launches rarer in the USA than in the rest of the world? Why?

Protected custom settings as a parameter in an @AuraEnabled method causes error

Why did NASA use U.S customary units?

kids pooling money for Lego League and taxes

how to add 1 milliseconds on a datetime string?

Will LSST make a significant increase in the rate of astronomical event alerts?

Keeping an "hot eyeball planet" wet

What is the difference between 1/3, 1/2, and full casters?

Where to place an artificial gland in the human body?

High income, sudden windfall

How do I run a game when my PCs have different approaches to combat?

Is there a published campaign where a missing artifact or a relic is creating trouble by its absence?

What is the meaning of "you has the wind of me"?

Terence Tao - type books in other fields?

What exactly makes a General Products hull nearly indestructible?

Is an easily guessed plot twist a good plot twist?

What are the exact meanings of roll, pitch and yaw?

How can I tell if there was a power cut while I was out?

What do teaching faculty do during semester breaks?

Sextortion with actual password not found in leaks

What does Kasparov mean here?

Inadvertently nuked my disk permission structure - why?

Very basic singly linked list



How to change checkbox in react correctly?


How do JavaScript closures work?How do I check if an element is hidden in jQuery?How to change an element's class with JavaScript?How do I remove a property from a JavaScript object?Setting “checked” for a checkbox with jQuery?How do I redirect to another webpage?How do I correctly clone a JavaScript object?How to check whether a checkbox is checked in jQuery?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








26















What is the correct way to change checkbox value?



option 1



import React, useState from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App()
const [x, setX] = useState(false);

const soldCheckbox = ( target: checked ) =>
console.log(x, checked);
setX(checked);
;
return (
<div>
<input type="checkbox" checked=x onChange=soldCheckbox />
</div>
);


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


option 2



import React, useState from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App()
const [x, setX] = useState(false);
console.log(x);
return (
<div>
<input type="checkbox" checked=x onChange=() => setX(!x) />
</div>
);


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


In fact, I think there's no difference, but I just wanted to hear a different opinion. Maybe something I do not know or there may be other solutions to this problem.










share|improve this question



















  • 3





    Both are correct, however abstracting the method from the input might be beneficial if you´re planning on reusing that method.

    – Webbanditten
    Jul 15 at 12:31






  • 3





    in this specific case, I would have chosen option 2, cleaner code in my opinion, setX changes the state, no need for a func calling setX and extracting the value from event if we know the value is x

    – Roy.B
    Jul 15 at 12:35


















26















What is the correct way to change checkbox value?



option 1



import React, useState from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App()
const [x, setX] = useState(false);

const soldCheckbox = ( target: checked ) =>
console.log(x, checked);
setX(checked);
;
return (
<div>
<input type="checkbox" checked=x onChange=soldCheckbox />
</div>
);


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


option 2



import React, useState from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App()
const [x, setX] = useState(false);
console.log(x);
return (
<div>
<input type="checkbox" checked=x onChange=() => setX(!x) />
</div>
);


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


In fact, I think there's no difference, but I just wanted to hear a different opinion. Maybe something I do not know or there may be other solutions to this problem.










share|improve this question



















  • 3





    Both are correct, however abstracting the method from the input might be beneficial if you´re planning on reusing that method.

    – Webbanditten
    Jul 15 at 12:31






  • 3





    in this specific case, I would have chosen option 2, cleaner code in my opinion, setX changes the state, no need for a func calling setX and extracting the value from event if we know the value is x

    – Roy.B
    Jul 15 at 12:35














26












26








26








What is the correct way to change checkbox value?



option 1



import React, useState from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App()
const [x, setX] = useState(false);

const soldCheckbox = ( target: checked ) =>
console.log(x, checked);
setX(checked);
;
return (
<div>
<input type="checkbox" checked=x onChange=soldCheckbox />
</div>
);


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


option 2



import React, useState from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App()
const [x, setX] = useState(false);
console.log(x);
return (
<div>
<input type="checkbox" checked=x onChange=() => setX(!x) />
</div>
);


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


In fact, I think there's no difference, but I just wanted to hear a different opinion. Maybe something I do not know or there may be other solutions to this problem.










share|improve this question
















What is the correct way to change checkbox value?



option 1



import React, useState from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App()
const [x, setX] = useState(false);

const soldCheckbox = ( target: checked ) =>
console.log(x, checked);
setX(checked);
;
return (
<div>
<input type="checkbox" checked=x onChange=soldCheckbox />
</div>
);


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


option 2



import React, useState from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App()
const [x, setX] = useState(false);
console.log(x);
return (
<div>
<input type="checkbox" checked=x onChange=() => setX(!x) />
</div>
);


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


In fact, I think there's no difference, but I just wanted to hear a different opinion. Maybe something I do not know or there may be other solutions to this problem.







javascript reactjs checkbox






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 16 at 9:38









Georgia Lumley

448 bronze badges




448 bronze badges










asked Jul 15 at 12:29









KlytaimnestraKlytaimnestra

3001 silver badge6 bronze badges




3001 silver badge6 bronze badges







  • 3





    Both are correct, however abstracting the method from the input might be beneficial if you´re planning on reusing that method.

    – Webbanditten
    Jul 15 at 12:31






  • 3





    in this specific case, I would have chosen option 2, cleaner code in my opinion, setX changes the state, no need for a func calling setX and extracting the value from event if we know the value is x

    – Roy.B
    Jul 15 at 12:35













  • 3





    Both are correct, however abstracting the method from the input might be beneficial if you´re planning on reusing that method.

    – Webbanditten
    Jul 15 at 12:31






  • 3





    in this specific case, I would have chosen option 2, cleaner code in my opinion, setX changes the state, no need for a func calling setX and extracting the value from event if we know the value is x

    – Roy.B
    Jul 15 at 12:35








3




3





Both are correct, however abstracting the method from the input might be beneficial if you´re planning on reusing that method.

– Webbanditten
Jul 15 at 12:31





Both are correct, however abstracting the method from the input might be beneficial if you´re planning on reusing that method.

– Webbanditten
Jul 15 at 12:31




3




3





in this specific case, I would have chosen option 2, cleaner code in my opinion, setX changes the state, no need for a func calling setX and extracting the value from event if we know the value is x

– Roy.B
Jul 15 at 12:35






in this specific case, I would have chosen option 2, cleaner code in my opinion, setX changes the state, no need for a func calling setX and extracting the value from event if we know the value is x

– Roy.B
Jul 15 at 12:35













7 Answers
7






active

oldest

votes


















16














I think that it all depends on the situation.



The first option will be better if you have a lot of form and components. You can handle all with one handler.



const handler = (e) => 
const target = e;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target;

setForm( f => ( ...f, [name]: value ));
;


Second, if checkbox is one and the application must somehow react to its change.
there is a third way to uncontrolled inputs.






share|improve this answer






























    9














    Both ways are almost the same, but the first option actually is more redundant, let's analyze why:



    Both the first and second methods are implementing controlled components



    This means that you are providing a value and a way to change it, so the responsibility to update and control the values are abstracted from the component.



    But why the first way is redundant?



    You don't actually need to read from the e.target.checked cause it always reflects the local state x, so there is no need to read from e.target.checked and reverse it by doing: setX(!e.target.checked) since x and the e.target.checked will always be the same.




    Caveats



    Even though is fine to do onClick=e => parentHandler(e) in a inline expression(arrow function) you should be careful, passing it like this to an input won't cause any problems, but when you are passing to a child component that implements React.memo or PureComponent for example, this will actually re render the component everytime, cause a new instance of the function is always created (signature is the same, but the shallow comparison will always return false cause they are different instances), so for optimization reasons is always best pass props like this: <Child onClick=this.clickHandler id=item.id /> and on the child: onClick=() => this.props.onClick(this.props.id) instead of just: <Child onClick=e => this.onClick(item.id) />







    share|improve this answer























    • want to say that option 2 is faster than option 1 ? 2 options also have redundant action.how can you compare it all?

      – Klytaimnestra
      Jul 15 at 22:47











    • Not faster. Just semantics

      – Dupocas
      Jul 15 at 22:59











    • I understood you correctly ?.Option 1 is faster, option 2 is clean.

      – Klytaimnestra
      Jul 15 at 23:10











    • Both runtimes are pretty much the same. The only thing that changes is semantic. Both ways are perfectly fine

      – Dupocas
      Jul 15 at 23:37



















    7














    In this specific case, I would have chosen option 2, cleaner code in my opinion.



    setX changes the state, no need for a function calling setX and extracting the value from event if we know the value is x.






    share|improve this answer






























      1














      The only difference is clean coding, first way is better if you need to do something except changing state (for example to call an http request) and the second is good if you just need checkbox to work and store its value.






      share|improve this answer






























        1














        It looks like both of your options are equivalent. If we look at the documentation for the onChange event provided by React (not the change event provided by html) it states:




        The onChange event behaves as you would expect it to: whenever a form field is changed, this event is fired.



        We intentionally do not use the existing browser behavior because onChange is a misnomer for its behavior and React relies on this event to handle user input in real time.



        https://reactjs.org/docs/dom-elements.html#onchange




        So, simply choose the option that you think produces cleaner code.






        share|improve this answer


















        • 4





          Well, in the same directories written, creating functions in this onChange=() => setX(!x) way is not always correct and may affect performance.

          – Klytaimnestra
          Jul 15 at 23:23











        • Are you saying that the value of x will sometimes be incorrect? or are you saying that declaring inline functions as props is a bad practice? I thought the OP was asking about the first question.

          – Xantix
          Jul 16 at 0:11






        • 2





          2. declaring inline functions.. it is so written in documentation.

          – Klytaimnestra
          Jul 16 at 0:30


















        1














        import React, useState from "react";
        import ReactDOM from "react-dom";

        import "./styles.css";

        function App()
        const [x, setX] = useState(false);

        const soldCheckbox = ( target: checked ) =>
        console.log(x, checked);
        setX(checked);
        ;
        return (
        <div>
        <input type="checkbox" checked=x onChange=soldCheckbox />
        </div>
        );


        const rootElement = document.getElementById("root");
        ReactDOM.render(<App />, rootElement);





        share|improve this answer


















        • 4





          It's great that you took the time to try and answer the question, though you should really consider adding some explanation rather than just pasting a snippet.

          – li x
          Jul 16 at 12:06


















        0














        I'm always choosing option 1 because it is a way more generic way for defining form field change events. In most of the cases, I have something in generic form components



        function SomeForm() 
        const [formData, setFormData] = useState( name: "", accept: false );
        const onFieldChange = ( target: name, value, checked ) =>
        if (typeof checked !== 'undefined') // checking if we have a "checked" field inside target
        setFormData( [name]: checked );


        setFormData( [name]: value );


        return (
        <form>
        <input type="text" name="name" value=formData.name onChange=onFieldChange />
        <input type="checkbox" name="accept" checked=formData.accept onChange=onFieldChange />
        </form>
        )



        The idea behind this is that any way we are going to receive a target DOM object which contains both checked and value, so we can make it generic.



        Hope this helps






        share|improve this answer

























          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%2f57039792%2fhow-to-change-checkbox-in-react-correctly%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          16














          I think that it all depends on the situation.



          The first option will be better if you have a lot of form and components. You can handle all with one handler.



          const handler = (e) => 
          const target = e;
          const value = target.type === 'checkbox' ? target.checked : target.value;
          const name = target;

          setForm( f => ( ...f, [name]: value ));
          ;


          Second, if checkbox is one and the application must somehow react to its change.
          there is a third way to uncontrolled inputs.






          share|improve this answer



























            16














            I think that it all depends on the situation.



            The first option will be better if you have a lot of form and components. You can handle all with one handler.



            const handler = (e) => 
            const target = e;
            const value = target.type === 'checkbox' ? target.checked : target.value;
            const name = target;

            setForm( f => ( ...f, [name]: value ));
            ;


            Second, if checkbox is one and the application must somehow react to its change.
            there is a third way to uncontrolled inputs.






            share|improve this answer

























              16












              16








              16







              I think that it all depends on the situation.



              The first option will be better if you have a lot of form and components. You can handle all with one handler.



              const handler = (e) => 
              const target = e;
              const value = target.type === 'checkbox' ? target.checked : target.value;
              const name = target;

              setForm( f => ( ...f, [name]: value ));
              ;


              Second, if checkbox is one and the application must somehow react to its change.
              there is a third way to uncontrolled inputs.






              share|improve this answer













              I think that it all depends on the situation.



              The first option will be better if you have a lot of form and components. You can handle all with one handler.



              const handler = (e) => 
              const target = e;
              const value = target.type === 'checkbox' ? target.checked : target.value;
              const name = target;

              setForm( f => ( ...f, [name]: value ));
              ;


              Second, if checkbox is one and the application must somehow react to its change.
              there is a third way to uncontrolled inputs.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jul 15 at 13:26









              Rich WarriorRich Warrior

              6011 silver badge6 bronze badges




              6011 silver badge6 bronze badges























                  9














                  Both ways are almost the same, but the first option actually is more redundant, let's analyze why:



                  Both the first and second methods are implementing controlled components



                  This means that you are providing a value and a way to change it, so the responsibility to update and control the values are abstracted from the component.



                  But why the first way is redundant?



                  You don't actually need to read from the e.target.checked cause it always reflects the local state x, so there is no need to read from e.target.checked and reverse it by doing: setX(!e.target.checked) since x and the e.target.checked will always be the same.




                  Caveats



                  Even though is fine to do onClick=e => parentHandler(e) in a inline expression(arrow function) you should be careful, passing it like this to an input won't cause any problems, but when you are passing to a child component that implements React.memo or PureComponent for example, this will actually re render the component everytime, cause a new instance of the function is always created (signature is the same, but the shallow comparison will always return false cause they are different instances), so for optimization reasons is always best pass props like this: <Child onClick=this.clickHandler id=item.id /> and on the child: onClick=() => this.props.onClick(this.props.id) instead of just: <Child onClick=e => this.onClick(item.id) />







                  share|improve this answer























                  • want to say that option 2 is faster than option 1 ? 2 options also have redundant action.how can you compare it all?

                    – Klytaimnestra
                    Jul 15 at 22:47











                  • Not faster. Just semantics

                    – Dupocas
                    Jul 15 at 22:59











                  • I understood you correctly ?.Option 1 is faster, option 2 is clean.

                    – Klytaimnestra
                    Jul 15 at 23:10











                  • Both runtimes are pretty much the same. The only thing that changes is semantic. Both ways are perfectly fine

                    – Dupocas
                    Jul 15 at 23:37
















                  9














                  Both ways are almost the same, but the first option actually is more redundant, let's analyze why:



                  Both the first and second methods are implementing controlled components



                  This means that you are providing a value and a way to change it, so the responsibility to update and control the values are abstracted from the component.



                  But why the first way is redundant?



                  You don't actually need to read from the e.target.checked cause it always reflects the local state x, so there is no need to read from e.target.checked and reverse it by doing: setX(!e.target.checked) since x and the e.target.checked will always be the same.




                  Caveats



                  Even though is fine to do onClick=e => parentHandler(e) in a inline expression(arrow function) you should be careful, passing it like this to an input won't cause any problems, but when you are passing to a child component that implements React.memo or PureComponent for example, this will actually re render the component everytime, cause a new instance of the function is always created (signature is the same, but the shallow comparison will always return false cause they are different instances), so for optimization reasons is always best pass props like this: <Child onClick=this.clickHandler id=item.id /> and on the child: onClick=() => this.props.onClick(this.props.id) instead of just: <Child onClick=e => this.onClick(item.id) />







                  share|improve this answer























                  • want to say that option 2 is faster than option 1 ? 2 options also have redundant action.how can you compare it all?

                    – Klytaimnestra
                    Jul 15 at 22:47











                  • Not faster. Just semantics

                    – Dupocas
                    Jul 15 at 22:59











                  • I understood you correctly ?.Option 1 is faster, option 2 is clean.

                    – Klytaimnestra
                    Jul 15 at 23:10











                  • Both runtimes are pretty much the same. The only thing that changes is semantic. Both ways are perfectly fine

                    – Dupocas
                    Jul 15 at 23:37














                  9












                  9








                  9







                  Both ways are almost the same, but the first option actually is more redundant, let's analyze why:



                  Both the first and second methods are implementing controlled components



                  This means that you are providing a value and a way to change it, so the responsibility to update and control the values are abstracted from the component.



                  But why the first way is redundant?



                  You don't actually need to read from the e.target.checked cause it always reflects the local state x, so there is no need to read from e.target.checked and reverse it by doing: setX(!e.target.checked) since x and the e.target.checked will always be the same.




                  Caveats



                  Even though is fine to do onClick=e => parentHandler(e) in a inline expression(arrow function) you should be careful, passing it like this to an input won't cause any problems, but when you are passing to a child component that implements React.memo or PureComponent for example, this will actually re render the component everytime, cause a new instance of the function is always created (signature is the same, but the shallow comparison will always return false cause they are different instances), so for optimization reasons is always best pass props like this: <Child onClick=this.clickHandler id=item.id /> and on the child: onClick=() => this.props.onClick(this.props.id) instead of just: <Child onClick=e => this.onClick(item.id) />







                  share|improve this answer













                  Both ways are almost the same, but the first option actually is more redundant, let's analyze why:



                  Both the first and second methods are implementing controlled components



                  This means that you are providing a value and a way to change it, so the responsibility to update and control the values are abstracted from the component.



                  But why the first way is redundant?



                  You don't actually need to read from the e.target.checked cause it always reflects the local state x, so there is no need to read from e.target.checked and reverse it by doing: setX(!e.target.checked) since x and the e.target.checked will always be the same.




                  Caveats



                  Even though is fine to do onClick=e => parentHandler(e) in a inline expression(arrow function) you should be careful, passing it like this to an input won't cause any problems, but when you are passing to a child component that implements React.memo or PureComponent for example, this will actually re render the component everytime, cause a new instance of the function is always created (signature is the same, but the shallow comparison will always return false cause they are different instances), so for optimization reasons is always best pass props like this: <Child onClick=this.clickHandler id=item.id /> and on the child: onClick=() => this.props.onClick(this.props.id) instead of just: <Child onClick=e => this.onClick(item.id) />








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 15 at 14:13









                  DupocasDupocas

                  2,6871 gold badge3 silver badges21 bronze badges




                  2,6871 gold badge3 silver badges21 bronze badges












                  • want to say that option 2 is faster than option 1 ? 2 options also have redundant action.how can you compare it all?

                    – Klytaimnestra
                    Jul 15 at 22:47











                  • Not faster. Just semantics

                    – Dupocas
                    Jul 15 at 22:59











                  • I understood you correctly ?.Option 1 is faster, option 2 is clean.

                    – Klytaimnestra
                    Jul 15 at 23:10











                  • Both runtimes are pretty much the same. The only thing that changes is semantic. Both ways are perfectly fine

                    – Dupocas
                    Jul 15 at 23:37


















                  • want to say that option 2 is faster than option 1 ? 2 options also have redundant action.how can you compare it all?

                    – Klytaimnestra
                    Jul 15 at 22:47











                  • Not faster. Just semantics

                    – Dupocas
                    Jul 15 at 22:59











                  • I understood you correctly ?.Option 1 is faster, option 2 is clean.

                    – Klytaimnestra
                    Jul 15 at 23:10











                  • Both runtimes are pretty much the same. The only thing that changes is semantic. Both ways are perfectly fine

                    – Dupocas
                    Jul 15 at 23:37

















                  want to say that option 2 is faster than option 1 ? 2 options also have redundant action.how can you compare it all?

                  – Klytaimnestra
                  Jul 15 at 22:47





                  want to say that option 2 is faster than option 1 ? 2 options also have redundant action.how can you compare it all?

                  – Klytaimnestra
                  Jul 15 at 22:47













                  Not faster. Just semantics

                  – Dupocas
                  Jul 15 at 22:59





                  Not faster. Just semantics

                  – Dupocas
                  Jul 15 at 22:59













                  I understood you correctly ?.Option 1 is faster, option 2 is clean.

                  – Klytaimnestra
                  Jul 15 at 23:10





                  I understood you correctly ?.Option 1 is faster, option 2 is clean.

                  – Klytaimnestra
                  Jul 15 at 23:10













                  Both runtimes are pretty much the same. The only thing that changes is semantic. Both ways are perfectly fine

                  – Dupocas
                  Jul 15 at 23:37






                  Both runtimes are pretty much the same. The only thing that changes is semantic. Both ways are perfectly fine

                  – Dupocas
                  Jul 15 at 23:37












                  7














                  In this specific case, I would have chosen option 2, cleaner code in my opinion.



                  setX changes the state, no need for a function calling setX and extracting the value from event if we know the value is x.






                  share|improve this answer



























                    7














                    In this specific case, I would have chosen option 2, cleaner code in my opinion.



                    setX changes the state, no need for a function calling setX and extracting the value from event if we know the value is x.






                    share|improve this answer

























                      7












                      7








                      7







                      In this specific case, I would have chosen option 2, cleaner code in my opinion.



                      setX changes the state, no need for a function calling setX and extracting the value from event if we know the value is x.






                      share|improve this answer













                      In this specific case, I would have chosen option 2, cleaner code in my opinion.



                      setX changes the state, no need for a function calling setX and extracting the value from event if we know the value is x.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 15 at 12:49









                      Roy.BRoy.B

                      9243 silver badges15 bronze badges




                      9243 silver badges15 bronze badges





















                          1














                          The only difference is clean coding, first way is better if you need to do something except changing state (for example to call an http request) and the second is good if you just need checkbox to work and store its value.






                          share|improve this answer



























                            1














                            The only difference is clean coding, first way is better if you need to do something except changing state (for example to call an http request) and the second is good if you just need checkbox to work and store its value.






                            share|improve this answer

























                              1












                              1








                              1







                              The only difference is clean coding, first way is better if you need to do something except changing state (for example to call an http request) and the second is good if you just need checkbox to work and store its value.






                              share|improve this answer













                              The only difference is clean coding, first way is better if you need to do something except changing state (for example to call an http request) and the second is good if you just need checkbox to work and store its value.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jul 15 at 12:47









                              Robert MinasyanRobert Minasyan

                              734 bronze badges




                              734 bronze badges





















                                  1














                                  It looks like both of your options are equivalent. If we look at the documentation for the onChange event provided by React (not the change event provided by html) it states:




                                  The onChange event behaves as you would expect it to: whenever a form field is changed, this event is fired.



                                  We intentionally do not use the existing browser behavior because onChange is a misnomer for its behavior and React relies on this event to handle user input in real time.



                                  https://reactjs.org/docs/dom-elements.html#onchange




                                  So, simply choose the option that you think produces cleaner code.






                                  share|improve this answer


















                                  • 4





                                    Well, in the same directories written, creating functions in this onChange=() => setX(!x) way is not always correct and may affect performance.

                                    – Klytaimnestra
                                    Jul 15 at 23:23











                                  • Are you saying that the value of x will sometimes be incorrect? or are you saying that declaring inline functions as props is a bad practice? I thought the OP was asking about the first question.

                                    – Xantix
                                    Jul 16 at 0:11






                                  • 2





                                    2. declaring inline functions.. it is so written in documentation.

                                    – Klytaimnestra
                                    Jul 16 at 0:30















                                  1














                                  It looks like both of your options are equivalent. If we look at the documentation for the onChange event provided by React (not the change event provided by html) it states:




                                  The onChange event behaves as you would expect it to: whenever a form field is changed, this event is fired.



                                  We intentionally do not use the existing browser behavior because onChange is a misnomer for its behavior and React relies on this event to handle user input in real time.



                                  https://reactjs.org/docs/dom-elements.html#onchange




                                  So, simply choose the option that you think produces cleaner code.






                                  share|improve this answer


















                                  • 4





                                    Well, in the same directories written, creating functions in this onChange=() => setX(!x) way is not always correct and may affect performance.

                                    – Klytaimnestra
                                    Jul 15 at 23:23











                                  • Are you saying that the value of x will sometimes be incorrect? or are you saying that declaring inline functions as props is a bad practice? I thought the OP was asking about the first question.

                                    – Xantix
                                    Jul 16 at 0:11






                                  • 2





                                    2. declaring inline functions.. it is so written in documentation.

                                    – Klytaimnestra
                                    Jul 16 at 0:30













                                  1












                                  1








                                  1







                                  It looks like both of your options are equivalent. If we look at the documentation for the onChange event provided by React (not the change event provided by html) it states:




                                  The onChange event behaves as you would expect it to: whenever a form field is changed, this event is fired.



                                  We intentionally do not use the existing browser behavior because onChange is a misnomer for its behavior and React relies on this event to handle user input in real time.



                                  https://reactjs.org/docs/dom-elements.html#onchange




                                  So, simply choose the option that you think produces cleaner code.






                                  share|improve this answer













                                  It looks like both of your options are equivalent. If we look at the documentation for the onChange event provided by React (not the change event provided by html) it states:




                                  The onChange event behaves as you would expect it to: whenever a form field is changed, this event is fired.



                                  We intentionally do not use the existing browser behavior because onChange is a misnomer for its behavior and React relies on this event to handle user input in real time.



                                  https://reactjs.org/docs/dom-elements.html#onchange




                                  So, simply choose the option that you think produces cleaner code.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jul 15 at 23:08









                                  XantixXantix

                                  3,0331 gold badge10 silver badges25 bronze badges




                                  3,0331 gold badge10 silver badges25 bronze badges







                                  • 4





                                    Well, in the same directories written, creating functions in this onChange=() => setX(!x) way is not always correct and may affect performance.

                                    – Klytaimnestra
                                    Jul 15 at 23:23











                                  • Are you saying that the value of x will sometimes be incorrect? or are you saying that declaring inline functions as props is a bad practice? I thought the OP was asking about the first question.

                                    – Xantix
                                    Jul 16 at 0:11






                                  • 2





                                    2. declaring inline functions.. it is so written in documentation.

                                    – Klytaimnestra
                                    Jul 16 at 0:30












                                  • 4





                                    Well, in the same directories written, creating functions in this onChange=() => setX(!x) way is not always correct and may affect performance.

                                    – Klytaimnestra
                                    Jul 15 at 23:23











                                  • Are you saying that the value of x will sometimes be incorrect? or are you saying that declaring inline functions as props is a bad practice? I thought the OP was asking about the first question.

                                    – Xantix
                                    Jul 16 at 0:11






                                  • 2





                                    2. declaring inline functions.. it is so written in documentation.

                                    – Klytaimnestra
                                    Jul 16 at 0:30







                                  4




                                  4





                                  Well, in the same directories written, creating functions in this onChange=() => setX(!x) way is not always correct and may affect performance.

                                  – Klytaimnestra
                                  Jul 15 at 23:23





                                  Well, in the same directories written, creating functions in this onChange=() => setX(!x) way is not always correct and may affect performance.

                                  – Klytaimnestra
                                  Jul 15 at 23:23













                                  Are you saying that the value of x will sometimes be incorrect? or are you saying that declaring inline functions as props is a bad practice? I thought the OP was asking about the first question.

                                  – Xantix
                                  Jul 16 at 0:11





                                  Are you saying that the value of x will sometimes be incorrect? or are you saying that declaring inline functions as props is a bad practice? I thought the OP was asking about the first question.

                                  – Xantix
                                  Jul 16 at 0:11




                                  2




                                  2





                                  2. declaring inline functions.. it is so written in documentation.

                                  – Klytaimnestra
                                  Jul 16 at 0:30





                                  2. declaring inline functions.. it is so written in documentation.

                                  – Klytaimnestra
                                  Jul 16 at 0:30











                                  1














                                  import React, useState from "react";
                                  import ReactDOM from "react-dom";

                                  import "./styles.css";

                                  function App()
                                  const [x, setX] = useState(false);

                                  const soldCheckbox = ( target: checked ) =>
                                  console.log(x, checked);
                                  setX(checked);
                                  ;
                                  return (
                                  <div>
                                  <input type="checkbox" checked=x onChange=soldCheckbox />
                                  </div>
                                  );


                                  const rootElement = document.getElementById("root");
                                  ReactDOM.render(<App />, rootElement);





                                  share|improve this answer


















                                  • 4





                                    It's great that you took the time to try and answer the question, though you should really consider adding some explanation rather than just pasting a snippet.

                                    – li x
                                    Jul 16 at 12:06















                                  1














                                  import React, useState from "react";
                                  import ReactDOM from "react-dom";

                                  import "./styles.css";

                                  function App()
                                  const [x, setX] = useState(false);

                                  const soldCheckbox = ( target: checked ) =>
                                  console.log(x, checked);
                                  setX(checked);
                                  ;
                                  return (
                                  <div>
                                  <input type="checkbox" checked=x onChange=soldCheckbox />
                                  </div>
                                  );


                                  const rootElement = document.getElementById("root");
                                  ReactDOM.render(<App />, rootElement);





                                  share|improve this answer


















                                  • 4





                                    It's great that you took the time to try and answer the question, though you should really consider adding some explanation rather than just pasting a snippet.

                                    – li x
                                    Jul 16 at 12:06













                                  1












                                  1








                                  1







                                  import React, useState from "react";
                                  import ReactDOM from "react-dom";

                                  import "./styles.css";

                                  function App()
                                  const [x, setX] = useState(false);

                                  const soldCheckbox = ( target: checked ) =>
                                  console.log(x, checked);
                                  setX(checked);
                                  ;
                                  return (
                                  <div>
                                  <input type="checkbox" checked=x onChange=soldCheckbox />
                                  </div>
                                  );


                                  const rootElement = document.getElementById("root");
                                  ReactDOM.render(<App />, rootElement);





                                  share|improve this answer













                                  import React, useState from "react";
                                  import ReactDOM from "react-dom";

                                  import "./styles.css";

                                  function App()
                                  const [x, setX] = useState(false);

                                  const soldCheckbox = ( target: checked ) =>
                                  console.log(x, checked);
                                  setX(checked);
                                  ;
                                  return (
                                  <div>
                                  <input type="checkbox" checked=x onChange=soldCheckbox />
                                  </div>
                                  );


                                  const rootElement = document.getElementById("root");
                                  ReactDOM.render(<App />, rootElement);






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jul 16 at 7:36









                                  Shraddha KharatShraddha Kharat

                                  425 bronze badges




                                  425 bronze badges







                                  • 4





                                    It's great that you took the time to try and answer the question, though you should really consider adding some explanation rather than just pasting a snippet.

                                    – li x
                                    Jul 16 at 12:06












                                  • 4





                                    It's great that you took the time to try and answer the question, though you should really consider adding some explanation rather than just pasting a snippet.

                                    – li x
                                    Jul 16 at 12:06







                                  4




                                  4





                                  It's great that you took the time to try and answer the question, though you should really consider adding some explanation rather than just pasting a snippet.

                                  – li x
                                  Jul 16 at 12:06





                                  It's great that you took the time to try and answer the question, though you should really consider adding some explanation rather than just pasting a snippet.

                                  – li x
                                  Jul 16 at 12:06











                                  0














                                  I'm always choosing option 1 because it is a way more generic way for defining form field change events. In most of the cases, I have something in generic form components



                                  function SomeForm() 
                                  const [formData, setFormData] = useState( name: "", accept: false );
                                  const onFieldChange = ( target: name, value, checked ) =>
                                  if (typeof checked !== 'undefined') // checking if we have a "checked" field inside target
                                  setFormData( [name]: checked );


                                  setFormData( [name]: value );


                                  return (
                                  <form>
                                  <input type="text" name="name" value=formData.name onChange=onFieldChange />
                                  <input type="checkbox" name="accept" checked=formData.accept onChange=onFieldChange />
                                  </form>
                                  )



                                  The idea behind this is that any way we are going to receive a target DOM object which contains both checked and value, so we can make it generic.



                                  Hope this helps






                                  share|improve this answer



























                                    0














                                    I'm always choosing option 1 because it is a way more generic way for defining form field change events. In most of the cases, I have something in generic form components



                                    function SomeForm() 
                                    const [formData, setFormData] = useState( name: "", accept: false );
                                    const onFieldChange = ( target: name, value, checked ) =>
                                    if (typeof checked !== 'undefined') // checking if we have a "checked" field inside target
                                    setFormData( [name]: checked );


                                    setFormData( [name]: value );


                                    return (
                                    <form>
                                    <input type="text" name="name" value=formData.name onChange=onFieldChange />
                                    <input type="checkbox" name="accept" checked=formData.accept onChange=onFieldChange />
                                    </form>
                                    )



                                    The idea behind this is that any way we are going to receive a target DOM object which contains both checked and value, so we can make it generic.



                                    Hope this helps






                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      I'm always choosing option 1 because it is a way more generic way for defining form field change events. In most of the cases, I have something in generic form components



                                      function SomeForm() 
                                      const [formData, setFormData] = useState( name: "", accept: false );
                                      const onFieldChange = ( target: name, value, checked ) =>
                                      if (typeof checked !== 'undefined') // checking if we have a "checked" field inside target
                                      setFormData( [name]: checked );


                                      setFormData( [name]: value );


                                      return (
                                      <form>
                                      <input type="text" name="name" value=formData.name onChange=onFieldChange />
                                      <input type="checkbox" name="accept" checked=formData.accept onChange=onFieldChange />
                                      </form>
                                      )



                                      The idea behind this is that any way we are going to receive a target DOM object which contains both checked and value, so we can make it generic.



                                      Hope this helps






                                      share|improve this answer













                                      I'm always choosing option 1 because it is a way more generic way for defining form field change events. In most of the cases, I have something in generic form components



                                      function SomeForm() 
                                      const [formData, setFormData] = useState( name: "", accept: false );
                                      const onFieldChange = ( target: name, value, checked ) =>
                                      if (typeof checked !== 'undefined') // checking if we have a "checked" field inside target
                                      setFormData( [name]: checked );


                                      setFormData( [name]: value );


                                      return (
                                      <form>
                                      <input type="text" name="name" value=formData.name onChange=onFieldChange />
                                      <input type="checkbox" name="accept" checked=formData.accept onChange=onFieldChange />
                                      </form>
                                      )



                                      The idea behind this is that any way we are going to receive a target DOM object which contains both checked and value, so we can make it generic.



                                      Hope this helps







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered yesterday









                                      Tigran BayburtsyanTigran Bayburtsyan

                                      802 silver badges11 bronze badges




                                      802 silver badges11 bronze badges



























                                          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%2f57039792%2fhow-to-change-checkbox-in-react-correctly%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

                                          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                                          Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

                                          Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?