Skip to content

Instantly share code, notes, and snippets.

@cgadski
Created October 19, 2021 13:02
Show Gist options
  • Select an option

  • Save cgadski/96977bc17741d8bc06541376f7902869 to your computer and use it in GitHub Desktop.

Select an option

Save cgadski/96977bc17741d8bc06541376f7902869 to your computer and use it in GitHub Desktop.
import { useState } from 'react'
function Child(props: { close: () => void }): JSX.Element {
return (
<button onClick={props.close}>click me to close</button>
)
}
export default function Parent(): JSX.Element {
// this works
let [state, setState] = useState(false)
let open = () => { setState(!state) }
let close = () => { setState(!state) }
let expanded = () => state
// but if you replace the previous four lines with these ...
// let [state, setState] = useState({ expanded: false })
// let open = () => { setState({expanded: true }) }
// let close = () => { setState({expanded: false }) }
// let expanded = () => state.expanded
// it doesn't: the Child stays open when you press the button
return (
<a onClick={open}>
<p>click me to open</p>
{expanded() && <Child close={close} />}
</a>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment