skip to Main Content

I know this topic has been discussed many times and I have already tried a few things.

Initially the checkbox is not checked, which is correct. At the first click hasTableHeader is still false and only at the second click hasTableHeader changes the state to true, which is wrong, because the input then is unchecked. I would be very grateful for any hints.

import  React, { useState } from 'react';
const [hasTableHeader, setHasTableHeader] = useState(false);

const handleHeaderChange = () => {
    setHasTableHeader(!hasTableHeader)
}

return (
  ...
   <input type="checkbox" checked={hasTableHeader} onChange={handleHeaderChange}/>
  ...
 )

3

Answers


  1. If you want to change state to opposite of current boolean state in react you can try :

    Functional component

    setHasTableHeader(prev=>!prev)
    

    Class component

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

    In your case the code you’re looking for here :

    import React , {useState} from 'react'
    
    export default function CheckboxComponent() {
      const [hasTableHeader, setHasTableHeader] = useState(false);
    
      const handleHeaderChange = () => {
        setHasTableHeader(prev=>!prev)
      }
    
      return (
         <input type="checkbox" checked={hasTableHeader} onChange={handleHeaderChange} />
      )
    }
    

    You can use this component anywhere like this :

    import CheckboxComponent from './CheckboxComponent'
    
    <CheckboxComponent />
    
    Login or Signup to reply.
  2. works fine as react function component for me:

    import { useState } from 'react';
    
    function MyCheckBox() {
      const [hasTableHeader, setHasTableHeader] = useState(false);
      const handleHeaderChange = () => {
        setHasTableHeader(!hasTableHeader)
      }
    
      return (
         <input type="checkbox" checked={hasTableHeader} onChange={handleHeaderChange}/>
       )
    }
    

    can then be used somewhere else like this: <MyCheckBox/>

    Login or Signup to reply.
  3. I think that your problem is somewhere else, because code is correct.

    const { useState } = React;
    
    
    const App = () => {
      const [hasTableHeader, setHasTableHeader] = useState(false);
    
      const handleHeaderChange = () => {
        setHasTableHeader(!hasTableHeader)
      }
      
      return (
        <input type="checkbox" checked={hasTableHeader} onChange={handleHeaderChange} /> 
      );
    };
    
    
    ReactDOM.render(<App />, document.getElementById('root'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
    <div id="root"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search