[javascript] How to toggle boolean state of react component?

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:

constructor(props, context) { 
   super(props, context);

   this.state = {
      check: false
   };
};

I am trying to toggle the state each time my checkbox is clicked, using the this.setState method:

<label><input type=checkbox" value="check" onChange = {(e) => this.setState({check: !check.value})}/> Checkbox </label>

Of course I get a Uncaught ReferenceError: check is not defined. So how can I achieve this?

Many thanks in advance.

This question is related to javascript reactjs reactjs-flux

The answer is


Use checked to get the value. During onChange, checked will be true and it will be a type of boolean.

Hope this helps!

_x000D_
_x000D_
class A extends React.Component {_x000D_
  constructor() {_x000D_
    super()_x000D_
    this.handleCheckBox = this.handleCheckBox.bind(this)_x000D_
    this.state = {_x000D_
      checked: false_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  handleCheckBox(e) {_x000D_
    this.setState({_x000D_
      checked: e.target.checked_x000D_
    })_x000D_
  }_x000D_
  _x000D_
  render(){_x000D_
    return <input type="checkbox" onChange={this.handleCheckBox} checked={this.state.checked} />_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<A/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_


Set: const [state, setState] = useState(1);

Toggle: setState(state*-1);

Use: state > 0 ? 'on' : 'off';


Depending on your context; this will allow you to update state given the mouseEnter function. Either way, by setting a state value to either true:false you can update that state value given any function by setting it to the opposing value with !this.state.variable

state = {
  hover: false
}

onMouseEnter = () => {
  this.setState({
    hover: !this.state.hover
  });
};

You should use this.state.check instead of check.value here:

this.setState({check: !this.state.check})

But anyway it is bad practice to do it this way. Much better to move it to separate method and don't write callbacks directly in markup.


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


Here's an example using hooks (requires React >= 16.8.0)

_x000D_
_x000D_
// import React, { useState } from 'react';_x000D_
const { useState } = React;_x000D_
_x000D_
function App() {_x000D_
  const [checked, setChecked] = useState(false);_x000D_
  const toggleChecked = () => setChecked(value => !value);_x000D_
  return (_x000D_
    <input_x000D_
      type="checkbox"_x000D_
      checked={checked}_x000D_
      onChange={toggleChecked}_x000D_
    />_x000D_
  );_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"><div>
_x000D_
_x000D_
_x000D_


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.


Try:

<label><input type=checkbox" value="check" onChange = {(e) => this.setState({check: !this.state.check.value})}/> Checkbox </label>

Using check: !check.value means it is looking for the check object, which you haven't declared.

You need to specify that you want the opposite value of this.state.check.


I found this the most simple when toggling boolean values. Simply put if the value is already true then it sets it to false and vice versa. Beware of undefined errors, make sure your property was defined before executing

this.setState({
   propertyName: this.propertyName = !this.propertyName
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to reactjs-flux

How to toggle boolean state of react component? How to make a rest post call from ReactJS code? how to cancel/abort ajax request in axios Having services in React application How to download fetch response in react as file How to submit a form using Enter key in react.js? Why use Redux over Facebook Flux? Expected corresponding JSX closing tag for input Reactjs