I\'d like to know how to toggle a boolean state of a react component. For instance:
I have boolean state check in the constructor of my component:
const
You could also use React's useState hook to declare local state for a function component. The initial state of the variable toggled
has been passed as an argument to the method .useState
.
import { render } from 'react-dom';
import React from "react";
type Props = {
text: string,
onClick(event: React.MouseEvent<HTMLButtonElement>): void,
};
export function HelloWorldButton(props: Props) {
const [toggled, setToggled] = React.useState(false); // returns a stateful value, and a function to update it
return <button
onClick={(event) => {
setToggled(!toggled);
props.onClick(event);
}}
>{props.text} (toggled: {toggled.toString()})</button>;
}
render(<HelloWorldButton text='Hello World' onClick={() => console.log('clicked!')} />, document.getElementById('root'));
https://stackblitz.com/edit/react-ts-qga3vc
I was landed in this page when I am searching to use toggle state in React component using Redux but I don't find here any approach using the same.
So, I think it might help someone who was struggling to implement toggle state using Redux.
My reducer file goes here. I get the initial state false by default.
const INITIAL_STATE = { popup: false };
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case "POPUP":
return {
...state,
popup: action.value
};
default:
return state;
}
return state;
};
I change state on clicking the image. So, my img tag goes here with onClick function.
<img onClick={togglePopup} src={props.currentUser.image} className="avatar-image avatar-image--icon" />
My Toggle Popup function goes below, which call Dispatcher.
const togglePopup = ev => {
ev.preventDefault();
props.handlePopup(!props.popup);
};
This call goes to below mapDispatchToProps function which reflects back the toggled state.
const mapDispatchToProps = dispatch => ({
handlePopup: value => dispatch({ type: "POPUP", value })
});
Thank you.
Since nobody posted this, I am posting the correct answer. If your new state update depends on the previous state, always use the functional form of setState
which accepts as argument a function that returns a new state.
In your case:
this.setState(prevState => ({
check: !prevState.check
}));
See docs
Since this answer is becoming popular, adding the approach that should be used for React Hooks (v16.8+):
If you are using the useState hook, then use the following code (in case your new state depends on the previous state):
const [check, setCheck] = useState(false);
// ...
setCheck(prevCheck => !prevCheck);