Created
December 17, 2021 04:59
-
-
Save Neo42/30fede378aad290be3d4520577f3eb9d to your computer and use it in GitHub Desktop.
React Patterns: Prop Collections and Getters
This file contains 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
// 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