Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useDuplex #38

Open
Drapegnik opened this issue Oct 27, 2018 · 3 comments
Open

useDuplex #38

Drapegnik opened this issue Oct 27, 2018 · 3 comments

Comments

@Drapegnik
Copy link

Drapegnik commented Oct 27, 2018

React hook for duplex buttons state:

Image from Gyazo

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

cc @jamiebuilds

@jamiebuilds
Copy link
Member

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

@jamesplease
Copy link
Member

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.

@Drapegnik
Copy link
Author

@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>
  );
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants