0

Problem: React Hook "React.useEffect" is called in function "selectmenu" which is neither a React function component or a custom React Hook function.

Target: I want to Mount Component('component DidMount/WillUnmount) (using useEffect()) only when I click on a button, rather than, mounting while the file (or whole Component) is being loaded.

Actual Goal: I want to select(or highlight) a file (custom ) on click. But when the user clicks outside the dimensions of the file (), then the selected file should get deselected (remove highlight).

export default function Academics() {
  let [ ismenuselected, setmenuselection] = useState(0)

  const selectmenu = () => {

    console.log("Menu to Select")

    React.useEffect(() => {
      console.log('Component DidMount/WillUnmount')

      return () => {
         console.log('Component Unmounted')
      }
    }, [isfolderselected]);
  }

  return (
          <div onClick={selectmenu}></div>
  )
}

Note:

  1. I've tried with the UPPER case of SelectFolder #56462812. Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
  2. I want to try something like this. But with a click of a button (useEffect() should invoke onClick event).
kartik tyagi
  • 6,256
  • 2
  • 14
  • 31
  • 2
    You can't put a hook in a callback. This is covered in the official rules of hooks faq in the react docs. You will need to toggle some state and then check that in a condition in your unconditionally called effect hook. – Jared Smith Jul 12 '20 at 20:24
  • thanks @JaredSmith. I make it worked by using `Class Component` and `CompounentDidMount` – kartik tyagi Jul 13 '20 at 04:57

1 Answers1

1

I think I got what you're trying to accomplish. First, you can't define a hook inside a function. What you can do is trigger the effect callback after at least one of its dependencies change.

useEffect(() => {
  // run code whenever deps change
}, [deps])

Though for this particular problem (from what I understood from your description), I'd go something like this:

export default function Academics() {
  let [currentOption, setCurrentOption] = useState()

  function handleSelectOption(i) {
    return () => setCurrentOption(i)
  }

  function clearSelectedOption() {
    return setCurrentOption()
  }

  return (options.map((option, i) =>
    <button
      onClick={handleSelectOption(i)}
      className={i === currentOption ? 'option option--highlight' : 'option'}
      onBlur={clearSelectedOption}
    ></button>
  ))
}

nicodp
  • 2,362
  • 1
  • 11
  • 20