Home > Blockchain >  How to create Bootstrap-like shorthand props for React components?
How to create Bootstrap-like shorthand props for React components?

Time:12-01

What is the best way to achieve this behavior along with React TypeScript?

import { Button, Card } from 'src/components';

const Page = () => (
  <div>
    <Card mx3 p3 flex justifyContentEnd>
      /* Card content */
    </Card>
    <Button my2 mx3>
      Login
    </Button>
  </div>
);

For instance, mx3 will add 16px margin horizontally, my2 will add 8px margin vertically, etc., similar to how the Bootstrap framework uses classes to apply utility styles easily.

I have looked through a few component libraries with this sort of behavior in order to find a suitable solution; however, I find most do not have strong typing support. Examples are RNUILib, NativeBase, Magnus UI, etc.

CodePudding user response:

If you see the source code of react-bootstrap, they have mapped the boolean to some CSS class using a util function of classnames package. You can do the same:

...
...
        <Component
          {...buttonProps}
          {...props}
          ref={ref}
          className={classNames(
            className,
            prefix,
            active && 'active',
            variant && `${prefix}-${variant}`,
            size && `${prefix}-${size}`,
            props.href && props.disabled && 'disabled',
          )}
        />
...
...

CodePudding user response:

You can declare your props like that:

const styles = ['mx3', 'p3', 'flex'] as const

type Styles = Record<typeof styles[number], boolean>;

Then use them like this:

type CardProps = Styles & {
  other: 'props here'
}

Now, this should work:

<Card mx3 p3 flex />

You can get applied props like this:

const values = Object.entries(props).map(([key, value]) => value ? key : null).filter(Boolean)
  • Related