Gathering detailed insights and metrics for react-with-styles
Gathering detailed insights and metrics for react-with-styles
Gathering detailed insights and metrics for react-with-styles
Gathering detailed insights and metrics for react-with-styles
react-with-styles-interface-css
Interface for react-with-styles outputting CSS
react-with-styles-interface-aphrodite
react-with-styles interface for Aphrodite
@types/react-with-styles
TypeScript definitions for react-with-styles
eslint-plugin-react-with-styles
ESLint plugin for react-with-styles
Use CSS-in-JavaScript with themes for React without being tightly coupled to one implementation
npm install react-with-styles
71.6
Supply Chain
94.3
Quality
81.8
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,705 Stars
285 Commits
95 Forks
49 Watching
86 Branches
27 Contributors
Updated on 25 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-3.7%
82,345
Compared to previous day
Last week
3.5%
431,679
Compared to previous week
Last month
6.7%
1,839,685
Compared to previous month
Last year
-22.8%
23,432,500
Compared to previous year
3
28
Maintenance Mode: This project is currently in maintenance mode and will eventually be archived. More info
Use CSS-in-JavaScript for your React components without being tightly coupled to one implementation (e.g. Aphrodite, Radium, or React Native). Easily access shared theme information (e.g. colors, fonts) when defining your styles.
Create a module that exports an object with shared theme information like colors.
1export default { 2 color: { 3 primary: '#FF5A5F', 4 secondary: '#00A699', 5 }, 6};
You will need to choose the react-with-styles
interface that corresponds to the underlying CSS-in-JS framework that you use in your app. Look through the list of existing interfaces, or write your own!
If you choose to write your own, the interface must implement the following functions:
Function | Description |
---|---|
create | Function that outputs the styles object injected through props.(Optional, but required if createLTR is not provided). |
createLTR | LTR version of create .(Required, unless a create function is provided) |
createRTL | RTL version of create .(Required, unless a create function is provided) |
resolve | This is the css function that is injected through props. It outputs the attributes used to style an HTML element.(Optional, but required if no resolveLTR is provided) |
resolveLTR | LTR version of resolve .(Required, unless the resolve function is provided) |
resolveRTL | RTL version of resolve .(Required, unless the resolve function is provided) |
flush? | Flush buffered styles before rendering. This can mean anything you need to happen before rendering. (Optional) |
☝️ Requires React 16.6+
As of version 4.0.0
, registering the theme and interface can be accomplished through React context, and is the recommended way of registering the theme, interface, and direction.
For example, if your theme is exported by MyTheme.js
, and you want to use Aphrodite through the react-with-styles-interface-aphrodite
interface, wrap your application with the WithStylesContext.Provider
to provide withStyles
with that interface and theme:
1import React from 'react'; 2import WithStylesContext from 'react-with-styles/lib/WithStylesContext'; 3import AphroditeInterface from 'react-with-styles-interface-aphrodite'; 4import MyTheme from './MyTheme'; 5 6export default function Bootstrap({ direction }) { 7 return ( 8 <WithStylesContext.Provider 9 value={{ 10 stylesInterface: AphroditeInterface, 11 stylesTheme: MyTheme, 12 direction, 13 }} 14 > 15 <App /> 16 </WithStylesContext.Provider> 17 ); 18}
To support people using a right-to-left (RTL) context, we recommend using react-with-styles
along with react-with-direction
. You can provide the direction directly if you have a utility that determines it like in the example above, or you can use the provided utility, WithStylesDirectionAdapter
, to grab the direction that's already been set on the react-with-direction
context and amend WithStylesContext
with it.
1import React from 'react'; 2import WithStylesContext from 'react-with-styles/lib/WithStylesContext'; 3import WithStylesDirectionAdapter from 'react-with-styles/lib/providers/WithStylesDirectionAdapter'; 4import AphroditeInterface from 'react-with-styles-interface-aphrodite'; 5import MyTheme from './MyTheme'; 6 7export default function Bootstrap() { 8 return ( 9 <WithStylesContext.Provider 10 value={{ 11 stylesInterface: AphroditeInterface, 12 stylesTheme: MyTheme, 13 }} 14 > 15 <WithStylesDirectionAdapter> 16 <App /> 17 </WithStylesDirectionAdapter> 18 </WithStylesContext.Provider> 19 ); 20}
Or simply wrap the Bootstrap
function above in withDirection
yourself.
☝️ Note on performance: Changing the theme many times will cause components to recalculate their styles. Avoid recalculating styles by providing one theme at the highest possible level of your app.
The legacy singleton-based API (using ThemedStyleSheet
) is still supported, so you can still use it to register the theme and interface. You do not have to do this if you use the WithStylesContext.Provider
. Keep in mind that this API will be deprecated in the next major version of react-with-styles
. You can set this up in your own withStyles.js
file, like so:
1import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet'; 2import AphroditeInterface from 'react-with-styles-interface-aphrodite'; 3import { withStyles } from 'react-with-styles'; 4 5import MyTheme from './MyTheme'; 6 7ThemedStyleSheet.registerTheme(MyTheme); 8ThemedStyleSheet.registerInterface(AphroditeInterface); 9 10export { withStyles, ThemedStyleSheet };
It is convenient to pass through withStyles
from react-with-styles
here so that everywhere you use them you can be assured that the theme and interface have been registered. You could likely also set this up as an initializer that is added to the top of your bundles and then use react-with-styles
directly in your components.
✋ Because the ThemedStyleSheet
implementation stores the theme and interface in variables outside of the React tree, we do not recommended it. This approach does not parallelize, especially if your build systems or apps require rendering with multiple themes.
In your components, use withStyles()
to define styles. This HOC will inject the right props to consume them through the CSS-in-JS implementation you chose.
1import React from 'react'; 2import PropTypes from 'prop-types'; 3import { withStyles, withStylesPropTypes } from './withStyles'; 4 5const propTypes = { 6 ...withStylesPropTypes, 7}; 8 9function MyComponent({ styles, css }) { 10 return ( 11 <div> 12 <a 13 href="/somewhere" 14 {...css(styles.firstLink)} 15 > 16 A link to somewhere 17 </a> 18 19 {' '} 20 and 21 {' '} 22 23 <a 24 href="/somewhere-else" 25 {...css(styles.secondLink)} 26 > 27 a link to somewhere else 28 </a> 29 </div> 30 ); 31} 32 33MyComponent.propTypes = propTypes; 34 35export default withStyles(({ color }) => ({ 36 firstLink: { 37 color: color.primary, 38 }, 39 40 secondLink: { 41 color: color.secondary, 42 }, 43}))(MyComponent);
You can also use the useStyles
hook or a decorator.
withStyles([ stylesThunk [, options ] ])
This is a higher-order function that returns a higher-order component used to wrap React components to add styles using the theme. We use this to make themed styles easier to work with.
stylesThunk
will receive the theme as an argument, and it should return an object containing the styles for the component.
The wrapped component will receive the following props:
styles
- Object containing the processed styles for this component. It corresponds to evaluating stylesInterface.create(stylesThunk(theme))
(or their directional counterparts).css
- Function to produce props to set the styles with on an element. It corresponds to stylesInterface.resolve
(or their directional counterparts).theme
- This is the theme object that was registered. You can use it during render as needed, say for inline styles.You can use withStyles()
as an HOC:
1import React from 'react'; 2import { withStyles } from './withStyles'; 3 4function MyComponent({ css, styles }) { 5 return ( 6 <div {...css(styles.container)}> 7 Try to be a rainbow in someone's cloud. 8 </div> 9 ); 10} 11 12export default withStyles(({ color, unit }) => ({ 13 container: { 14 color: color.primary, 15 marginBottom: 2 * unit, 16 }, 17}))(MyComponent);
As a decorator:
1import React from 'react'; 2import { withStyles } from './withStyles'; 3 4@withStyles(({ color, unit }) => ({ 5 container: { 6 color: color.primary, 7 marginBottom: 2 * unit, 8 }, 9})) 10export default function MyComponent({ styles, css }) { 11 return ( 12 <div {...css(styles.container)}> 13 Try to be a rainbow in someone's cloud. 14 </div> 15 ); 16}
You can also use the experimental hook:
1import React from 'react'; 2import useStyles from 'react-with-styles/lib/hooks/useStyles'; 3 4function stylesFn({ color, unit }) { 5 return ({ 6 container: { 7 color: color.primary, 8 marginBottom: 2 * unit, 9 }, 10 }); 11} 12 13export default function MyComponent() { 14 const { css, styles } = useStyles({ stylesFn }); 15 return ( 16 <div {...css(styles.container)}> 17 Try to be a rainbow in someone's cloud. 18 </div> 19 ); 20}
pureComponent
(default: false
)By default withStyles()
will create a functional component. If you want to apply the rendering optimizations offered by React.memo
, you can set the pureComponent
option to true
to create a pure functional component instead.
If using the withStyles
utility that is found in lib/deprecated/withStyles
, it will instead use a React.PureComponent
rather than a React.Component
. Note that this has a React version requirement of 15.3.0+.
stylesPropName
(default: 'styles'
)By default, withStyles()
will pass down the styles to the wrapped component in the styles
prop, but the name of this prop can be customized by setting the stylesPropName
option. This is useful if you already have a prop called styles
and aren't able to change it.
1import React from 'react'; 2import { withStyles, withStylesPropTypes } from './withStyles'; 3 4function MyComponent({ withStylesStyles, css }) { 5 return ( 6 <div {...css(withStylesStyles.container)}> 7 Try to be a rainbow in someone's cloud. 8 </div> 9 ); 10} 11 12MyComponent.propTypes = { 13 ...withStylesPropTypes, 14}; 15 16export default withStyles(({ color, unit }) => ({ 17 container: { 18 color: color.primary, 19 marginBottom: 2 * unit, 20 }, 21}), { stylesPropName: 'withStylesStyles' })(MyComponent);
cssPropName
(default 'css'
)The css prop name can also be customized by setting the cssPropName
option.
1import React from 'react'; 2import { withStyles, withStylesPropTypes } from './withStyles'; 3 4function MyComponent({ withStylesCss, styles }) { 5 return ( 6 <div {...withStylesCss(styles.container)}> 7 Try to be a rainbow in someone's cloud. 8 </div> 9 ); 10} 11 12MyComponent.propTypes = { 13 ...withStylesPropTypes, 14}; 15 16export default withStyles(({ color, unit }) => ({ 17 container: { 18 color: color.primary, 19 marginBottom: 2 * unit, 20 }, 21}), { cssPropName: 'withStylesCss' })(MyComponent);
themePropName
(default 'theme'
)The theme prop name can also be customized by setting the themePropName
option.
1import React from 'react'; 2import { withStyles, withStylesPropTypes } from './withStyles'; 3 4function MyComponent({ css, styles, withStylesTheme }) { 5 return ( 6 <div {...css(styles.container)}> 7 <Background color={withStylesTheme.color.primary}> 8 Try to be a rainbow in someone's cloud. 9 </Background> 10 </div> 11 ); 12} 13 14MyComponent.propTypes = { 15 ...withStylesPropTypes, 16}; 17 18export default withStyles(({ color, unit }) => ({ 19 container: { 20 color: color.primary, 21 marginBottom: 2 * unit, 22 }, 23}), { themePropName: 'withStylesTheme' })(MyComponent);
flushBefore
(default: false
)Some components depend on previous styles to be ready in the component tree when mounting (e.g. dimension calculations). Some interfaces add styles to the page asynchronously, which is an obstacle for this. So, we provide the option of flushing the buffered styles before the rendering cycle begins. It is up to the interface to define what this means.
css(...styles)
This function takes styles that were processed by withStyles()
, plain objects, or arrays of these things. It returns an object with attributes that must be spread into a JSX element. We recommend not inspecting the results and spreading them directly onto the element. In other words className
and style
props must not be used on the same elements as css()
.
1import React from 'react'; 2import { withStyles, withStylesPropTypes } from './withStyles'; 3 4const propTypes = { 5 ...withStylesPropTypes, 6}; 7 8function MyComponent({ css, styles, bold, padding, }) { 9 return ( 10 <div {...css(styles.container, { padding })}> 11 Try to be a rainbow in{' '} 12 <a 13 href="/somewhere" 14 {...css(styles.link, bold && styles.link_bold)} 15 > 16 someone's cloud 17 </a> 18 </div> 19 ); 20} 21 22MyComponent.propTypes = propTypes; 23 24export default withStyles(({ color, unit }) => ({ 25 container: { 26 color: color.primary, 27 marginBottom: 2 * unit, 28 }, 29 30 link: { 31 color: color.secondary, 32 }, 33 34 link_bold: { 35 fontWeight: 700, 36 }, 37}))(MyComponent);
React 16.3 introduced the ability to pass along refs with the React.forwardRef
helper, allowing you to write code like this.
1const MyComponent = React.forwardRef( 2 function MyComponent({ css, styles }, forwardedRef) { 3 return ( 4 <div {...css(styles.container)} ref={forwardedRef}> 5 Hello, World 6 </div> 7 ); 8 } 9);
Refs will not get passed through HOCs by default because ref
is not a prop. If
you add a ref to an HOC, the ref will refer to the outermost container component,
which is usually not desired. withStyles
is set up to pass along your ref to
the wrapped component.
1const MyComponentWithStyles = withStyles(({ color, unit }) => ({
2 container: {
3 color: color.primary,
4 marginBottom: 2 * unit,
5 },
6}))(MyComponent);
7
8// the ref will be passed down to MyComponent, which is then attached to the div
9const ref = React.createRef()
10<MyComponentWithStyles ref={ref} />
ThemedStyleSheet
(legacy)Registers themes and interfaces.
⚠️ Deprecation Warning: ThemedStyleSheet
is going to be deprecated in the next major version. Please migrate your applications to use WithStylesContext
to provide the theme and interface to use along with withStyles
or useStyles
. In the meantime, you should be able to use both inside your app for a smooth migration. If this is not the case, please file an issue so we can help.
ThemedStyleSheet.registerTheme(theme)
(legacy)Registers the theme. theme
is an object with properties that you want to be made available when styling your components.
1import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet'; 2 3ThemedStyleSheet.registerTheme({ 4 color: { 5 primary: '#FF5A5F', 6 secondary: '#00A699', 7 }, 8});
ThemedStyleSheet.registerInterface(interface)
(legacy)Instructs react-with-styles how to process your styles.
1import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet'; 2import AphroditeInterface from 'react-with-styles-interface-aphrodite'; 3 4ThemedStyleSheet.registerInterface(AphroditeInterface);
Link
React Router's <Link/>
and <IndexLink/>
components accept activeClassName='...'
and activeStyle={{...}}
as props. As previously stated, css(...styles)
must spread to JSX, so simply passing styles.thing
or even css(styles.thing)
directly will not work. In order to mimic activeClassName
/activeStyles
you can use React Router's withRouter()
Higher Order Component to pass router
as prop to your component and toggle styles based on router.isActive(pathOrLoc, indexOnly)
. This works because <Link />
passes down the generated className
from css(..styles)
down through to the final leaf.
1import React from 'react'; 2import { withRouter, Link } from 'react-router'; 3import { css, withStyles } from '../withStyles'; 4 5function Nav({ router, styles }) { 6 return ( 7 <div {...css(styles.container)}> 8 <Link 9 to="/" 10 {...css(styles.link, router.isActive('/', true) && styles.link_bold)} 11 > 12 home 13 </Link> 14 <Link 15 to="/somewhere" 16 {...css(styles.link, router.isActive('/somewhere', true) && styles.link_bold)} 17 > 18 somewhere 19 </Link> 20 </div> 21 ); 22} 23 24export default withRouter(withStyles(({ color, unit }) => ({ 25 container: { 26 color: color.primary, 27 marginBottom: 2 * unit, 28 }, 29 30 link: { 31 color: color.primary, 32 }, 33 34 link_bold: { 35 fontWeight: 700, 36 } 37}))(Nav));
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 8/12 approved changesets -- score normalized to 6
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More