#Is this the most optimal way to do a simple data toggler button?

4 messages · Page 1 of 1 (latest)

snow tide
#
import React from "react"

export default function Accordion({ children, title }) {

  const [toggle, setToggle] = React.useState(false);

  function handleClick(e) {
    e.preventDefault()
    setToggle(prevToggle => !prevToggle)
  }

  return (
    <div>
    <button onClick={handleClick}>{title}</button>
    {toggle ? <div>{children}</div> : null}
    </div>
  )
}

It works just fine, just making sure I am following best possible practices.

snow tide
#

minor changes :

  • remove e.preventDefault() if your Accordion component is not inside a form
  • change the outer div tag to a fragment if you dont plan on styling it :
    JSX
  </>``` 
- change the ternary statement to a conditional : 
```{toggle && JSX}```
#

minor changes, but doesnt affect your flow