rehooks/ideas

useDuplex

Opened this issue ยท 3 comments

React hook for duplex buttons state:

Image from Gyazo

https://github.com/Drapegnik/react-use-duplex

cc @jamiebuilds

Looks really cool, but I'm not sure it's generic enough to belong in rehooks. Maybe in a React design system/framework?

Agreed w. @jamiebuilds regarding generic-ness. As an aside, using radio inputs instead of managing the state yourself would likely reduce LoC and also allow you to scale to any number of buttons.

@jamiebuilds, @jamesplease

What's about the following api:

There are two modes: radio (when you just select one state from options) and duplex (when second click on selected item resets to default state)

const Toggle = () => {
  const [state, [{ onClick }]] = useDuplex(['on', 'off'], {
    mode: 'duplex',
    default: 'off',
    initial: 'on',
  });
  
  // state - 'on' | 'off'

  return (
    <div>
      <button onClick={onClick}>{state}</button>
    </div>
  );
};
const Duplex = () => {
  const [state, [approved, _, rejected]] = useDuplex(['approved', 'not-selected', 'rejected'], {
    mode: 'duplex',
    default: 'not-selected',
    initial: 'approved',
    // onChange
  });
  
  // approved: {
  //  onClick,
  //  pending,
  //  ...
  // }

  return (
    <div>
      <button onClick={approved.onClick}>
        {state === 'approved' ? 'Approved ๐Ÿ‘' : 'Approve'}
      </button>
      <button onClick={rejected.onClick}>
        {state === 'rejected' ? 'Rejected ๐Ÿ‘Ž' : 'Reject'}
      </button>
    </div>
  );
};
const RadioGroup = () => {
  const [state, options] = useDuplex(['male', 'female', 'other'], {
    mode: 'radio',
  });
  
  // state - null | 'male' | 'female' | 'other'

  return (
    <div>
      {options.map(({ value, onClick}) => (
        <button onClick={onClick}>{state === value && 'Selected: '}{value}</button>
      ))}
    </div>
  );
};