A simple way to include CSS with React Components.
Note: Work has moved over to @helpscout/fancy.
- Tiny, at less than 850 bytes gzipped
- Only one dependency - (Stylis)
- Write plain ol' CSS. Period.
- Built-in pre-processing when you need it. Powered by Stylis.
- Easily integrate with your setup. No extra webpack-loaders required.
npm install --save @helpscout/fancy
import React from 'react'
import { withStyles } from '@helpscout/fancy'
Write your CSS styles as a string. This is default out-of-the-box CSS. Use things like :hover
, @media
queries, as you normally would!
const css = `
.Button {
background: white;
border: 1px solid #eee;
}
`
Note: You can of course use string interpolation. It's still JS after all!
Create your component as you normally would.
const Button = props => (
<button className='Button' {...props} />
)
Note: The reference the CSS className
to match the CSS you wrote. Fancy does not generated uniquely hashed classNames for you. See CSS Modules for that feature.
When exporting your component, compose it with the withStyles
higher-order component along with your CSS styles.
export default withStyles(css)(Button)
import React from 'react'
import { withStyles } from '@helpscout/fancy'
const css = `
.Button {
background: white;
border: 1px solid #eee;
}
`
const Button = props => (
<button className='Button' {...props} />
)
export default withStyles(css)(Button)
<html>
<head>
<style type='text/css'>
.Button {
background: white;
border: 1px solid #eee;
}
</style>
</head>
<body>
...
<button class='Button'>Button</button>
...
</body>
</html>
That's it! You're done 🙌. You've created a CSS-ready component.
You can define dynamic styles by passing a function
into withStyles
. It will have access to a component's props
, allowing you to define custom rules for various prop
values.
const Card = props => (<div {...props} />)
const css = (props) => `
div {
background: ${props.title ? 'red' : 'blue'};
position: relative;
border: 1px solid black;
}
`
const StyledCard = withStyles(css)(Card)
This technique is similar to the ones found in Styled Components.