Giter VIP home page Giter VIP logo

merge-sx's Introduction

merge-sx

Coverage Status NPM Downloads NPM License

Combines multiple SxProps for Material UI components.

Installation

npm install merge-sx
# or
yarn add merge-sx

Usage

The utility provides a very simple and semantically clean interface, that supports conditional and optional inclusions.

import { mergeSx } from "merge-sx";

// Merge your SxProps
mergeSx(sx1, sx2 /*, ... */);
// Merge optionally
mergeSx(internalSx, props?.sx); // supports undefined
// Merge conditionally
mergeSx(commonSx, isMobile && mobileSx); // supports false

Why might you need it

MUI 5 has introduced a new way of styling React components using a Theme-aware sx property. It can be necessary to create your own styled components while still allowing for additional styling by the consumer. In this case your component will have its own sx property, most likely optional. This makes it necessary somehow to combine your own styles with the styles coming from the consumer of your component. One approach might be using a styling wrapper, an alternative way to style your component with the styled() utility. Thus, you could apply the consumer's sx to the pre-styled component. However, this approach can be inconvenient for several reasons.

I came to conclusion that merging several sx properties is better. However, the SxProps has rather complex data type. It can be an object with styling properties, can be function, can be null. It can be a challenge to perform a merge under strict typing of Typescript.

How it works

Luckily, starting version 5.1.0 of MUI SxProps can also be array. However, nested arrays are not allowed, so this utility does exactly the flat merge, also bringing support for conditional and optional inclusions, providing a very simple and semantically clean interface.

Performance

The utility has been tested to support up to 65535 arguments.

┌─────────────┬──────────┬─────────┬────────┬───────┐
│ N arguments │   10     │   100   │  1000  │ 10000 │
├─────────────┼──────────┼─────────┼────────┼───────┤
│ ops/s       │ 13615624 │ 1273083 │ 122746 │ 14686 │
└─────────────┴──────────┴─────────┴────────┴───────┘

Examples

Conditional merging

The utility supports false:

<Button sx={mergeSx(commonSx, isMobile && mobileSx)}>Click me</Button>

Optional merging

The utility supports undefined:

interface MyButtonProps {
  sx?: SxProps<Theme>; // optional prop for consumer
}

const MyButton = ({ sx: consumerSx }: MyButtonProps) => (
  <Button sx={mergeSx(internalSx, consumerSx)}>Click me</Button>
);

Inline Theme supplying

The utility is generic and accepts the type argument.

// theme is Theme
mergeSx<Theme>(sx1, (theme) => ({ mb: theme.spacing(1) }));

merge-sx's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar renovate[bot] avatar robintail avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

merge-sx's Issues

Update proposal

Nice lib! Thank you - this saved me a few hours on my initial investigation.
But it looks like I found an easier trick:

import { Theme } from "@mui/system";
import { SxProps } from "@mui/material";

export const mergeSx = <T extends Theme>(...styles: (SxProps<T> | false | undefined)[]): SxProps<T> => {
  return styles.flat(2).filter(Boolean) as SxProps<T>;
};

// not sure if Theme actually required:
export const mergeSx2 = (...styles: (SxProps | false | undefined)[]): SxProps => {
  return styles.flat(2).filter(Boolean) as SxProps;
};

// or even without filter if no need to support undefined in arguments
// since SxProps respects boolean in array, and then no need for type casting:
export const mergeSx3 = (...styles: (SxProps | false)[]): SxProps => styles.flat(2);

not sure about performance, but should be pretty fast I guess..

I end up using this trick like this:

<Box 
  sx={[
    localSx,
    { color: "green" },
    props.sx ?? false,
    !!props.major && { color: "red" },
  ].flat(2)}
>{props.children}</Box>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.