The Journey of #100DaysOfCode (@sourabhbagrecha)

#Day73 of #100daysofcode

Today my best friend @anshul_bhardwaj has also joined us in this adventure of #100daysofcode.
He is on his way to become a full-stack developer in the next few months, wish him luck.

As of my updates for today, I learned about prop-getters.
Sometimes the users of our hook might want to implement their own functions while at the same time they want to leverage all the props that our hooks provide by default, therefore we need to provide an API that will provide them the ability to add custom features that they want to be executed combinedly with the defaults.

In the following example, we are providing the ability to execute a custom onClick function alongside the default toggle function.

function useToggle() {
  const [on, setOn] = React.useState(false)
  const toggle = () => setOn(!on)

  return {
    on,
    toggle,
    getTogglerProps: ({onClick, ...props} = {}) => {
      return {
        'aria-pressed': on,
        onClick: () => {
          toggle()
          onClick()
        },
        ...props,
      }
    },
  }
}

function App() {
  const {on, getTogglerProps} = useToggle()
  return (
    <div>
      <Switch on={on} {...getTogglerProps()} />
      <hr />
      <button
        aria-label="custom-button"
        {...getTogglerProps({
          onClick: () => {
            console.log(
              `Calling inside a function that's passed to prop getters,
               to execute apart from the defaults provided by prop collections.`,
            )
          },
        })}
      >
        {on ? 'on' : 'off'}
      </button>
    </div>
  )
}
3 Likes