Created
November 3, 2021 16:01
-
-
Save rockchalkwushock/7bc6508afd0791361be2b92ba92307b4 to your computer and use it in GitHub Desktop.
Example of using a Toggler component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react' | |
type RenderProps = { | |
close: () => void | |
isOpen: boolean | |
open: () => void | |
toggle: () => void | |
} | |
type Props = { | |
children: (props: RenderProps) => React.ReactChild | |
initial?: boolean | |
} | |
export const Toggler: React.FC<Props> = ({ children, initial = false }) => { | |
const [state, setState] = React.useState(initial) | |
React.useEffect(() => { | |
// Prevents memory leak. | |
return () => {} | |
}) | |
return ( | |
<> | |
{children({ | |
close: () => setState(false), | |
isOpen: state, | |
open: () => setState(true), | |
toggle: () => setState(!state), | |
})} | |
</> | |
) | |
} | |
// Usage | |
type Props = { | |
item: Record<string, string> | |
onChange: (id: string) => void | |
} | |
const DeleteButton: React.FC<Props> = ({ children, item, onChange }) => { | |
return ( | |
<Toggler> | |
{({ close, isOpen, open }) => ( | |
<> | |
<button onClick={open}>{children}</button> | |
{isOpen && ( | |
<Modal> | |
<ModalHeader> | |
{children} | |
<ModalCloseButton onClick={close} /> | |
</ModalHeader> | |
<ModalBody> | |
<p>Are you sure you want to delete {item.name}?</p> | |
<p>This is a permanent operation and is not reversible!</p> | |
</ModalBody> | |
<ModalFooter> | |
<button onClick={close}>Cancel</button> | |
<button onClick={() => { | |
onChange(item.id) | |
close() | |
}> | |
Delete | |
</button> | |
</ModalFooter> | |
</Modal> | |
)} | |
</> | |
)} | |
</Toggler> | |
) | |
} | |
// Usage | |
<DeleteButton item={resource} onChange={(id) => asyncOperation(id)}>Delete Resource</DeleteButton> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment