Home > Net >  React functions arent getting invoked in a functional component
React functions arent getting invoked in a functional component

Time:12-06

import { useState } from 'react'

import { AiOutlinePlus } from 'react-icons/ai'

import { TimerForm } from './TimerForm'

export const ToggleAddTimer = () => {

const [formState, setFormState] = useState(false);

const handleFormOpen = () => {

setFormState(true);

}

const handleFormClose = () => {

setFormState(false);

}

if (formState) {

return (

  <TimerForm formClose={handleFormClose()} />

)

}

else {

return (

  <button onClick={() => {handleFormOpen()}}> this function isn't getting invoked
    <AiOutlinePlus/>
  </button>
)

} }

CodePudding user response:

Try <TimerForm formClose={handleFormClose} />

and in your else

<button onClick={() => handleFormOpen()}>

CodePudding user response:

Do this:

const [formState, setFormState] = useState(false)

const toggleFormState = () => {
  setFormState(state => !state);
}

<button onClick={toggleFormState}> 
   <AiOutlinePlus/>
</button>

Test:

function App() {
  
  const [formState, setFormState] = useState(false)
  
  const toggleFormState = () => {
     setFormState(state => !state);
  }

  return (
      <button onClick={toggleFormState}>
          Form State is {formState ? "true": "false"}
      </button>
  )
}

  • Related