How to change checkbox react correctly?Loop inside React JSXWhat do these three dots in React do?Programmatically navigate using react routerWhat is the difference between React Native and React?Route not defined react router and spring boot serverWebpack: You may need an appropriate loader to handle this file type. errortypescript not catching type mismatch (react TSX)web add-in load issues on Outlook desktop onlyReact Checkbox Depends on Parent StateFailed to compile error in react while trying to run the folder on terminal

Why did Spider-Man take a detour to Dorset?

Why use null function instead of == [] to check for empty list in Haskell?

Can I send medicine to someone in Canada?

Too many spies!

Getting fresh water in the middle of hypersaline lake in the Bronze Age

Accidentally deleted python and yum is not working in centos7

Video editor for YouTube

Was all the fuel expended in each stage of a Saturn V launch?

Why don't commercial aircraft adopt a slightly more seaplane-like design to allow safer ditching in case of emergency?

Sending a photo of my bank account card to the future employer

Why hasn't the U.S. government paid war reparations to any country it attacked?

What is the technical explanation of the note "A♭" in a F7 chord in the key of C?

Did the First Order follow Poe to Jakku, or did they independently discover that the map fragment was there?

Mathematica function equivalent to Matlab's residue function (partial fraction expansion)

I won USD 50K! Now what should I do with it?

Why limit to revolvers?

What does the BBL file-extension stand for in LaTeX?

What do mathematicians mean when they say some conjecture can’t be proven using the current technology?

Will it hurt my career to work as a graphic designer in a startup for beauty and skin care?

If I stood next to a piece of metal heated to a million degrees, but in a perfect vacuum, would I feel hot?

What are the benefits to casting without the need for somatic components?

How to calculate difference in AnyDice?

What to look for in climbing shoes?

What is this called? A tube flange bearing threaded for threaded pushrod



How to change checkbox react correctly?


Loop inside React JSXWhat do these three dots in React do?Programmatically navigate using react routerWhat is the difference between React Native and React?Route not defined react router and spring boot serverWebpack: You may need an appropriate loader to handle this file type. errortypescript not catching type mismatch (react TSX)web add-in load issues on Outlook desktop onlyReact Checkbox Depends on Parent StateFailed to compile error in react while trying to run the folder on terminal






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








11















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



















  • 1





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

    – Webbanditten
    10 hours ago






  • 2





    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
    10 hours ago


















11















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



















  • 1





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

    – Webbanditten
    10 hours ago






  • 2





    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
    10 hours ago














11












11








11








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.







reactjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 10 hours ago









El.

3215 silver badges12 bronze badges




3215 silver badges12 bronze badges










asked 10 hours ago









KlytaimnestraKlytaimnestra

1405 bronze badges




1405 bronze badges







  • 1





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

    – Webbanditten
    10 hours ago






  • 2





    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
    10 hours ago













  • 1





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

    – Webbanditten
    10 hours ago






  • 2





    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
    10 hours ago








1




1





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

– Webbanditten
10 hours ago





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

– Webbanditten
10 hours ago




2




2





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
10 hours ago






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
10 hours ago













4 Answers
4






active

oldest

votes


















3














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






























    2














    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 ?

      – Klytaimnestra
      5 mins ago


















    1














    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






























      0














      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

























        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-react-correctly%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        3














        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



























          3














          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

























            3












            3








            3







            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 9 hours ago









            Rich WarriorRich Warrior

            3163 bronze badges




            3163 bronze badges























                2














                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 ?

                  – Klytaimnestra
                  5 mins ago















                2














                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 ?

                  – Klytaimnestra
                  5 mins ago













                2












                2








                2







                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 8 hours ago









                DupocasDupocas

                1,8202 silver badges16 bronze badges




                1,8202 silver badges16 bronze badges












                • want to say that option 2 is faster than option 1 ?

                  – Klytaimnestra
                  5 mins ago

















                • want to say that option 2 is faster than option 1 ?

                  – Klytaimnestra
                  5 mins ago
















                want to say that option 2 is faster than option 1 ?

                – Klytaimnestra
                5 mins ago





                want to say that option 2 is faster than option 1 ?

                – Klytaimnestra
                5 mins ago











                1














                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














                  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












                    1








                    1







                    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 9 hours ago









                    Roy.BRoy.B

                    8543 silver badges15 bronze badges




                    8543 silver badges15 bronze badges





















                        0














                        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



























                          0














                          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

























                            0












                            0








                            0







                            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 10 hours ago









                            Robert MinasyanRobert Minasyan

                            383 bronze badges




                            383 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-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

                                Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480