css-provider
v2.4.17
Published
Brings the power of scoped CSS to your React components!
Downloads
24
Readme
CSS Provider
Description
CSSProvider is a wrapper component that allows you to write plain-ish CSS as a prop, which will then be given a unique identifier (to allow instance scoping), minified, and sent to a <style>
tag in the <head>
of the document.
The plain-ish part is of course the &
that is used as the id for the wrapper.
Props
Along with the following props
, the <CSSProvider>
component will also accept any props
allowed by the tag specified in the as
prop.
as
:[optional]
: Expects a string
representing the desired element tag to render the wrapper as. (Default is div
)
ref
:[optional]
: Expects a ref
created by using React's useRef()
hook or React.createRef()
. This ref
will be forwarded to the wrapper.
css
:[required]
: The CSS that will be rendered
There are two ways of passing data to this prop:
string
: (This will be written just like you would in a standard CSS file)
css={`
& {
color: blue;
}
`}
object
: (This will be written wth the selector being the property name, and the declaration block being written using react's style prop syntax)
css={{
'&': {
color: 'blue',
},
}}
This CSS will be injected into a <style>
tag which will be rendered in the <head>
of the document.
Because of this, it is important to remember to use &
to reference the wrapper
in your CSS, AND to use the &
as a preface for the children's styles.
Examples:
`& { ...declarations }`
-or-
`& > .child { ...declarations }`
-or-
'&:hover > .inner-span': { ...declarations }
IMPORTANT: If you go with prop option 2 (object) do not expect vendor prefixes to function properly.
Vendor prefixes like -ms
, -webkit
, etc. are considered experimental features.
This means that:
- The behaviour is likely to vary between browsers (bad)
- It may or may not be available in some browsers (bad)
- It may have to be explicitly enabled on some browsers (bad)
- Some browsers, like Chrome, are currently working on eliminating prefixes completely in future releases (very bad!)
It is best practice to avoid vendor prefixes at all costs, and to either find another way to achieve the result you're looking for or force the user to update their browser to have access to new CSS features.
To find out more about the availability of certain CSS rules (or JavaScript!) and whether you should use them, please visit caniuse.com and use your best judgement!
How To Use
To Install:
npm install css-provider
To Import:
import { CSSProvider } from 'css-provider';
A Simple Example:
function MyComponent(props) {
// Some code here
return (
<CSSProvider
css={`
& {
background-color: red;
}
& > span {
color: blue;
}
`}
>
<span>Some Text</span>
</CSSProvider>
);
}
The HTML document when <MyComponent/>
is used:
<head>
...
<style>
#cssp-style-1 {
background-color: red;
}
#cssp-style-1 > span {
color: blue;
}
</style>
...
</head>
<body>
...
<div id="cssp-style-1">
<span>Some Text</span>
</div>
...
</body>
Get Fancy With It
Need the wrapper to be a <button>
with a ref
? Want to include some props
or state
to make the CSS rules responsive? How about a simple style override/addition solution? Easy: 🤓
function MyComponent({
padding,
rounded = false,
backgroundColor = 'red',
wrapperStyleOverride = {}, // <--- Styles here will have a higher priority than the ones below
spanStyleOverride = {}, // <--- unless, of course, you use '!important' which is discouraged
}) {
const buttonRef = useRef();
const [textColor, setTextColor] = useState('blue');
// Some code here
return (
<CSSProvider
as="button" // <--- this will force the wrapper to render as a <button>
ref={buttonRef} // <--- this will be forwarded to the <button>
style={wrapperStyleOverride}
css={`
& {
padding: ${padding ?? '5px'}
background-color: ${backgroundColor};
border: 1px solid black;
${rounded && 'border-radius: 10px;'}
}
& > span {
color: ${textColor};
}
`}
>
<span style={spanStyleOverride}>Some Text</span>
</CSSProvider>
);
}
The <Style>
Tag
- Again, they are injected into the
<head>
of the document (It is bad practice to have them in the<body>
!!! 🙅♂️) - Only one is created, upon rendering of the first CSSProvider 👍
- It will re-render if the css changes, allowing the use of props and state within the CSS 😭
- All CSSProvider styles will be minified and compiled as one big CSS string 😁
- All CSSProviders clean themselves up by removing their associated rules from the
<style>
tag when the component unmounts. 😎
Some Big Advantages
- ✔ Eliminate re-created hover detection logic in components to achieve conditional/responsive styling
- ✔ Eliminate the need to write as much CSS by making its values depend on values from
props
andstate
- ✔ Have access to CSS's wonderful selectors and functions
- ✔ Stop heavy reliance on the
style
props in child components (which is limited and inefficient) and instead use them for those moments where a specific instance needs to be a little different form the rest
NEW as of @2.3.3
The css
prop now takes an object of selector: { ...declarations }
, using React's style prop syntax. 🤯
Example:
<CSSProvider
css={{
'&': {
backgroundColor: 'white',
},
'& > .label': {
color: 'black',
},
}}
>
<span className="label">some label</span>
</CSSProvider>
NEW as of @2.4.16
As web/software developers, it's important to remember Occam's Razor.
The package has now been stripped down to the basics! Enjoy a super small package size, and preserved documentation to study and understand if you wish. 👍
Because of the change, if you use an IDE like VSCode then using the object
syntax for the css
prop will allow for some CSS auto-completion and help keep the memory load off of that big fantastic brain of yours! 🧠❤