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;
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
add a comment |
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
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
add a comment |
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
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
reactjs
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
add a comment |
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
add a comment |
4 Answers
4
active
oldest
votes
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.
add a comment |
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 implementsReact.memoorPureComponentfor 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) />
want to say that option 2 is faster than option 1 ?
– Klytaimnestra
5 mins ago
add a comment |
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.
add a comment |
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.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
answered 9 hours ago
Rich WarriorRich Warrior
3163 bronze badges
3163 bronze badges
add a comment |
add a comment |
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 implementsReact.memoorPureComponentfor 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) />
want to say that option 2 is faster than option 1 ?
– Klytaimnestra
5 mins ago
add a comment |
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 implementsReact.memoorPureComponentfor 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) />
want to say that option 2 is faster than option 1 ?
– Klytaimnestra
5 mins ago
add a comment |
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 implementsReact.memoorPureComponentfor 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) />
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 implementsReact.memoorPureComponentfor 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) />
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
add a comment |
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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered 9 hours ago
Roy.BRoy.B
8543 silver badges15 bronze badges
8543 silver badges15 bronze badges
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered 10 hours ago
Robert MinasyanRobert Minasyan
383 bronze badges
383 bronze badges
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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