Andrew's Digital Garden

Prop getters

Prop getters help you hand rendering control over the users of the components. It's a function that when called, will return props, which must then be applied (usually spread) to the correct elements. This allows the component to contain the logic and remain consistent, while affording the user the change what is rendered to the page, e.g. a Toggle component that also allows control through a button.

Realistically this just an extension of [[20221205104221-render-props-pattern]] but instead of returning props directly, you return a function which affords the original component more control.

For example, the function can be extended to allow arguments, which can then be composed with the required props to hand even more control to the user. For example, this allows a user to add a custom onClick even if an onClick is returned from the function. The two functions can then be merged to ensure both are called and neither overwrites the other. Otherwise we'd have to explicitly call a prop from the prop getter which adds coupling we don't want and reduces maintainability. What the prop getter returns can be thought of as an implementation detail.

// A generic helper to check if a function exists, and if it does, call it const callAll = (...fns) => (...args) => fns.forEach(fn => fn?.(...args)) function getTogglerProps({onClick, ...props} = {}) { return { 'aria-pressed': on, onClick: callAll(onClick, toggle), ...props, } } const {on, getTogglerProps, getResetterProps} = useToggle({ reducer: toggleStateReducer, }) return ( <Switch {...getTogglerProps({ disabled: clickedTooMuch, on: on, onClick: () => setTimesClicked(count => count + 1), })} /> )

[[components]] [[react]] [[reactapi]]

Prop getters