React Pseudo State
The solution for handling pseudo-states when working with a CSS in JS solution.
Install
yarn add react-pseudo-state
Use
import PseudoState from 'react-pseudo-state'; const Button = children ...props <PseudoState> handlers snapshot <button = > children </button> </PseudoState>;
A higher-order-component is also provided if that's more your speed:
import withPseudoState from 'react-pseudo-state'; const ButtonElement = isActive ...props <button = />; const Button = ;
Keyboard support
The native browser behaviour is that Enter
is for anchors and buttons, whilst Space
is only called on buttons. To stay compliant it's recommended to dynamically populate the keyboardSupport
property.
The shape of keyboardSupport
is described below in the Types section. It will default to 'auto'
, which sniffs the event target for a node type.
import PseudoState from 'react-pseudo-state'; const Button = props <PseudoState => handlers snapshot propshref ? <a /> : <button />) </PseudoState>;
Types
The first argument to the children
function is an object of handlers, which must be spread onto the node returned from children
:
type Handlers = mixed mixed onKeyDown?: event: SyntheticKeyboardEvent<HTMLElement> mixed onKeyUp?: event: SyntheticKeyboardEvent<HTMLElement> mixed mixed mixed mixed mixed mixed mixed;
The second argument is the snapshot, or current state of the element:
type Snapshot = focusOrigin: null | 'keyboard' | 'mouse' isActive: boolean isFocus: boolean isHover: boolean;
The actual PseudoState
component only has two properties:
type Props = React$Node keyboardSupport: 'auto' | 'enter' | 'space' | 'both' | 'none';