Skip to content

Instantly share code, notes, and snippets.

@Neo42
Created December 17, 2021 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Neo42/30fede378aad290be3d4520577f3eb9d to your computer and use it in GitHub Desktop.
Save Neo42/30fede378aad290be3d4520577f3eb9d to your computer and use it in GitHub Desktop.
React Patterns: Prop Collections and Getters
// Prop Collections and Getters
// merge all passed functions into one
const mergeFn =
(...fns) =>
(...args) =>
fns.forEach(fn => fn?.(...args))
function useToggle() {
const [on, setOn] = React.useState(false)
const toggle = () => setOn(!on)
// 2. Wrap the common props object into
// a getter function to allow for custom props
const getTogglerProps = ({onClick, ...props}) => ({
// 1. Wrap commonly used props into an object
'aria-pressed': on,
onClick: mergeFn(toggle, onClick),
...props,
})
return {on, getTogglerProps}
}
function App() {
const {on, getTogglerProps} = useToggle()
return (
<div>
<Switch {...getTogglerProps({on})} />
<hr />
<button
{...getTogglerProps({
'aria-label': 'custom-button',
onClick: () => console.log('onButtonClick'),
id: 'custom-button-id',
})}
>
{on ? 'on' : 'off'}
</button>
</div>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment