Prop Getters
Loading "Prop Getters"
Run locally for transcripts
π¨βπΌ Uh oh! Someone wants to use our
togglerProps
object, but they need to apply
their own onClick
handler! Try doing that by updating the App
component to
this:function App() {
const { on, togglerProps } = useToggle()
return (
<div>
<Switch on={on} {...togglerProps} />
<hr />
<button
aria-label="custom-button"
{...togglerProps}
onClick={() => console.info('onButtonClick')}
>
{on ? 'on' : 'off'}
</button>
</div>
)
}
I want both the toggle to work as well as the log. Does that work? Why not? Can
you change it to make it work?
What if we change the API slightly so that instead of having an object of props,
we call a function to get the props. Then we can pass that function the props we
want applied and that function will be responsible for composing the props
together.
Let's try that. Our file has been updated to use a
new API we're responsible for creating. See if you can make that API work.
π¦Ί The types for the argument to the
getTogglerProps
component might be a bit
tricky, so here's a little tip: you can get the onClick
prop from:
React.ComponentProps<'button'>['onClick']
.