You are not changing state in right manner, Code for change state will be like this this.setState({ showCart: true}) Replace handleClick function from below code.

 handleClick() {
    this.setState({ showCart: true}) 
    console.log("button clicked")
  }
Answer from Nishant Dixit on Stack Overflow
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 70305075 โ€บ change-boolean-value-onclick-in-react
Change boolean value onClick in React - javascript
December 10, 2021 - First, decide what you are going to use and then fix the errors 1 by 1. The constructor for example is missing the props, there are onclicks that are not well defined and a few more things. Here is your code if used as a class component. import { Component } from "react"; export class App extends Component<{}, { offers: any[] }> { constructor(props: {}) { super(props); this.state = { offers: [], }; this.handleToggle = this.handleToggle.bind(this); } componentDidMount() { this.setState({ offers: Data }); } handleToggle(offers: any) { this.setState((prevState) => ({ offers: prevState.offers.map(
Discussions

How to toggle boolean state of a React component?
I'd like to know how to toggle a boolean state of a React component. For instance: I have a boolean state check in the constructor of my component: constructor(props, context) { super(props, co... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to conditionally add or not onClick on a div in react?
I would like to know if it is possible to set onClick on a div element in react based on the value of a property in my case canClick. I am aware that I can check this.state directly in handler ins... More on stackoverflow.com
๐ŸŒ stackoverflow.com
React needs two clicks to update boolean state when triggering button onClick event
I have a React functional component in which I have some input fields, a button, and a tooltip. The tooltip is disabled by default and should only be enabled and visible if the button is clicked wh... More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 3, 2023
reactjs - Warning: Expected `onClick` listener to be a function, instead got a value of `boolean` type - Stack Overflow
I am working with react. When I try to play audio from a button I am receiving this error. Everything worked before when the website was only a one page website. Then I turned it into a multi-page More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Medium
medium.com โ€บ @IkeoluwaAshade โ€บ clicking-button-to-toggle-a-boolean-state-8257b70fb293
Clicking button to toggle a Boolean state | by Ikeoluwa Ashade | Medium
June 20, 2024 - The return statement contains JSX to render the component. <button onClick={toggleChange}>Toggle</button> renders a button that when clicked upon, calls the toggleChange function to toggle the state.
๐ŸŒ
YouTube
youtube.com โ€บ arslan
Toggle Between Booleans OnClick Of A Button ReactJS - YouTube
antd: npm i antd;Simple toggle between booleans in reactJS using react statePlease don't forget Like, Comment and Subscribe if you're new! Support the channe...
Published ย  November 23, 2019
Views ย  26K
๐ŸŒ
JsCraft
js-craft.io โ€บ home โ€บ toggle a boolean value in the state of a react component โ€“ the right way
Toggle a boolean value in the state of a React component โ€“ the right way
September 9, 2021 - Let's say you have a button that will just toggle a boolean in the state of a React component: export const MyButtonComponent = (props) => { const [foo, setFoo] = useState(false); const handleClick = () => { /* to be added */}; return ( <button onClick={handleClick}>Toggle</button> ); } Initially for me, the most intuitive way to do it seemed to be: const handleClick = () => setFoo(!foo); However, it seems that this may lead to some corner-case (and very annoying) bugs.
๐ŸŒ
Dommagnifi
dommagnifi.co โ€บ 2020-12-03-toggle-state-with-react-hooks
Toggle State With React Hooks - Dominic Magnifico
n1 = !!true // !!truthy returns true n2 = !!{} // !!truthy returns true: any object is truthy... n3 = !!(new Boolean(false)) // ...even Boolean objects with a false .valueOf()! n4 = !!false // !!falsy returns false n5 = !!"" // !!falsy returns false n6 = !!Boolean(false) // !!falsy returns false ยท This section was mostly for my own edification. I wasn't 100% clear on the intent of the double not operator, but now we know! Let's use the logical not operator in our example to set the opposite value of the current state in our toggle button. import React, { useState } from 'react' const MyComponent = () => { const [toggle, setToggle] = useState(false) return( <> <button onClick={() => setToggle(!toggle)}>Toggle State</button> </> ) }
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 77219576 โ€บ react-needs-two-clicks-to-update-boolean-state-when-triggering-button-onclick-ev
React needs two clicks to update boolean state when triggering button onClick event
October 3, 2023 - const handleOnClick = (setIsInvalidValue: React.Dispatch<React.SetStateAction<boolean>>) => { if (fieldsInvalid()) { setIsInvalidValue(true); } else { setIsInvalidValue(false); } } const MyComponent = () => { const [enableTooltip, setEnableTooltip] = useState(false); const [isInvalidValue, setIsInvalidValue] = useState(false); useEffect(() => { setEnableTooltip(isInvalidValue); }, [isInvalidValue]); return ( <InputFields /> <Tooltip disabled={!enableTooltip}> <Button slot="trigger" onClick={() => handleOnClick(setIsInvalidValue)} /> Tooltip text </Tooltip> } }
๐ŸŒ
usehooks-ts
usehooks-ts.com โ€บ react-hook โ€บ use-boolean
useBoolean | usehooks-ts
import { useBoolean } from ... onClick={customToggle}>custom toggle</button> </> ) } ... Custom hook that handles boolean state with useful utility functions....
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ react-toggle-boolean-state
How to toggle a Boolean state in React | bobbyhadz
Copied!import {useEffect, useState} from 'react'; export default function App() { const [isLoading, setIsLoading] = useState(false); const toggleIsLoading = () => { // ๐Ÿ‘‡๏ธ Passed function to setState setIsLoading(current => !current); }; useEffect(() => { // ๐Ÿ‘‡๏ธ If you need to listen for changes of isLoading boolean console.log('isLoading is: ', isLoading); }, [isLoading]); return ( <div> <button onClick={toggleIsLoading}>Toggle loading state</button> {isLoading && <h2>bobbyhadz.com...</h2>} </div> ); } The code for this article is available on GitHub ยท
๐ŸŒ
DEV Community
dev.to โ€บ alexkhismatulin โ€บ update-boolean-state-right-with-react-hooks-3k2i
Update boolean state right with React Hooks - DEV Community
May 11, 2020 - const OptimizedBooleanState = () => { const [isToggled, toggle] = useToggle(false); const [randomNumber, setRandomNumber] = React.useState(Math.random()); const generateRandomNumber = React.useCallback( () => setRandomNumber(Math.random()), [], ); return ( <div> <div> Current random number is <b>{randomNumber}</b> <button style={{ marginLeft: '10px' }} onClick={generateRandomNumber}> regenerate </button> </div> <div> Boolean is set to <b>{String(isToggled)}</b>. </div> <RendersCounter onClick={toggle} /> </div> ); }
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ toggle-elements-in-react-using-hooks
How to Toggle an Element in React using React Hooks
April 16, 2025 - Above, we created a button that contains an onClick event handler using the setToggle setter previously declared above. Then we rendered the elements based on the boolean condition of the toggle variable when it gets clicked.
Top answer
1 of 2
2

Normal OOP design principles don't always apply directly to React components. Components don't usually have instance properties, they mostly just have props and state (there are a few exceptions where you do use an instance property, like Animation objects in react-native, but these are rare).

You're kind of mixing the two things in a way that doesn't quite make sense here. Settings is a React component that renders an image, but it's also an object which you instantiate by calling new Settings(). If there are other components which depend on the value of flag, you might want to separate the accessing and storing of the flag from the render component, passing a value and a callback to the renderer.

const Settings = ({setFlag}) => {
      return(
          <img src="./img/leaf.png" alt="" onClick={() => setFlag(true)}/>
      );
}

You've suggested that you like the Context API as a solution for making the flag value globally available. There are a few ways to set this up, but here's one.

Outside of any component, we create a FlagContext object that has two properties: a boolean value flag and callback function setFlag. We need to give it a default fallback value, which is hopefully never used, so our default callback just logs a warning and does nothing.

const FlagContext = createContext<FlagContextState>({
  flag: false,
  setFlag: () => console.warn("attempted to use FlagContext outside of a valid provider")
});

This FlagContext object gives up Provider and Consumer components, but it's up to us to give a value to the FlagContext.Provider. So we'll create a custom component that handles that part. Our custom FlagProvider uses a local state to create and pass down the value. I've used a function component, but you could use a class component as well.

const FlagProvider = ({children}) => {
  const [flag, setFlag] = useState(false);

  return (
    <FlagContext.Provider value={{
      flag,
      setFlag
    }}>
      {children}
    </FlagContext.Provider>
  )
}

We want to put the entire App inside of the FlagProvider so that the whole app has the potential to access flag and setFlag, and the whole app gets the same flag value.

When you want to use the value from the context in a component, you use either the useContext hook or the Consumer component. Either way, I like to creating an aliased name and export that rather than exporting the FlagContext object directly.

export const FlagConsumer = FlagContext.Consumer;

export const useFlagContext = () => useContext(FlagContext);

With the Consumer, the child of the consumer is a function that takes the value of the context, which in out case is an object with properties flag and setFlag, and returns some JSX.

This is usually a function you define inline:

const SomePage = () => {
  return (
    <FlagConsumer>
      {({flag, setFlag}) => (<div>Flag Value is {flag.toString()}</div>)}
    </FlagConsumer>
  )
}

But it can also be a function component. Note that when using a function component as the child, you must pass the component itself ({Settings}) rather than an executed version of it (<Settings />).

const Settings = ({ setFlag }) => {
  return <img src="./img/leaf.png" alt="" onClick={() => setFlag(true)} />;
};

const SomePage = () => {
  return <FlagConsumer>{Settings}</FlagConsumer>;
};

The preferred method nowadays is with hooks. We call useFlagContext() inside the body of the function component and it returns our context object.

const SomePage = () => {
  const {flag, setFlag} = useFlagContext();

  return <Settings setFlag={setFlag}/>
};

Both the consumer and the hook only work if they are inside of a flag context provider, so that's why we put it around the whole app!

const App = () => {
  return (
    <FlagProvider>
      <SomePage />
    </FlagProvider>
  );
};

Complete example on CodeSandbox

2 of 2
1

For this kind of interactions, I highly recommend you to use Redux

Another think I'm sure you will benefit from, is switching to hooks and function components: less boilerplate and much flexible code.

Back to the goal, using Redux your code would look similar to this:

const Settings = (props) => {
  const dispatch = useDispatch();
  const flag = useSelector(state => state.yourStoreObj.flag);
      
  handleClick() {
    dispatch(yourCustomAction("UPDATE_FLAG", true));
  }
  
  return(
        <img src="./img/leaf.png" alt="" onClick={() => handleClick()}/>
    );  
}

Explanation:

First of all, spend 15 mins and get used to React Redux. Here's a good practical article to start with. If you're not familiar with hooks, start learning them as that will change a lot, while you don't need to change a single line of what you've done so far.

We suppose there's a property in the store that is the "flag" property of that specific element. In this way, the property can be read by the component itself with the useSelector() operator, or can be read anywhere in your application with the same methodology from any other component.

In the same way, you can change the value by dispatching a change (see dispatch() function) and in the same way, you can do that from any other components.

So, let's say you want to change that property when a click occurs on a completely different component, this is how the other component may looks like

const OtherCoolComp = (props) => {
  const dispatch = useDispatch();
  
  handleClick() {
    dispatch(yourCustomAction("UPDATE_FLAG", true));
  }
  
  return(
        <button onClick={() => handleClick()}>
          Click me!
        </button>
    );  
}

So you're dispatching the same action, setting it to the value you prefer, from a component that doesn't know who is displaying that value.

๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ react โ€บ how do you show or hide elements in react?
How do you show or hide elements in React? | Sentry
January 30, 2023 - You can use the logical AND (&&) operator to conditionally render an element based on a boolean state value: export default function MyComponent() { const [isOpen, setIsOpen] = useState(false); function toggle() { setIsOpen((isOpen) => !isOpen); ...
๐ŸŒ
GitHub
github.com โ€บ facebook โ€บ react โ€บ issues โ€บ 11027
Loosen up type requirements for event handlers ยท Issue #11027 ยท facebook/react
October 2, 2017 - This was fine in React 15.x, but in 16 it reports a warning, which is technically correct: Expected onClick listener to be a function, instead got a value of boolean type. However, this now forces you to use the more verbose variant: const MyButton = ({ canClick, onClick }) => <div onClick={(canClick && onClick) ?
๐ŸŒ
React
legacy.reactjs.org โ€บ docs โ€บ handling-events.html
Handling Events โ€“ React
Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method. If calling bind annoys you, there are two ways you can get around this. You can use public class fields syntax to correctly bind callbacks: class LoggingButton extends React.Component { // This syntax ensures `this` is bound within handleClick.
๐ŸŒ
Selftaughttxg
selftaughttxg.com โ€บ 2023 โ€บ 04-23 โ€บ creating-a-true-false-toggle-in-react-with-usestate-hook-for-beginners
Creating a True/False Toggle in React with useState Hook for Beginners |
April 14, 2023 - Others believe that the change was unnecessary and that the original scene should have been left intact."; function toggleDidHanSoloShootFirst() { if(didHanSoloShootFirst === true) { setDidHanSoloShootFirst(false); } else if (didHanSoloShootFirst === false) { setDidHanSoloShootFirst(true); } } return ( <div className='container'> <button onClick={toggleDidHanSoloShootFirst}>Toggle Shoot</button> <h4>Did Han Solo shoot first? {didHanSoloShootFirst ? "Yes!" : "No!"}</h4> <img src={didHanSoloShootFirst ? HanShotFirst : HanShotSecond} /> <p>{didHanSoloShootFirst ? paragraphHanShotFirst : paragraphHanShotSecond}</p> </div> ); } export default HanSolo; Create a React Project, Push It to GitHub, and Deploy With Netlify, From the Command Line