DEV Community

Chan
Chan

Posted on

react-with-styles: basic usage

react-with-styles is one of the CSS-in-JS libraries. You can modify document's style in js files and most of the times it'd be inside Component if you chose to use React. Inside of it's related to HOC(Higher-Ordered Components).

  • install react-with-styles

> yarn add react-with-styles aphrodiete react-with-styles-interface-aphrodite

You should install not only install react-with-styles but also aphrodite. aphrodite helps you to render on server-side. JS Engline would start working with CSS(in js files) only after DOM drawing is finished. There're some delays to be done with CSS painting and that's when aphrodite plays a role.

  • withStyles.js
import ThemedStyleSheet from 'react-with-styles/lib/ThemedStyleSheet';
import aphroditeInterface from 'react-with-styles-interface-aphrodite';
import { css, withStyles, withStylesPropTypes } from 'react-with-styles';
import Theme from './Theme';

ThemedStyleSheet.registerTheme(Theme);
ThemedStyleSheet.registerInterface(aphroditeInterface);

export { css, withStyles, withStylesPropTypes, ThemedStyleSheet };
export default withStyles;
Enter fullscreen mode Exit fullscreen mode
  1. register Theme and export associated modules. Theme'll be applied to Component if you wrap it with withStyles() and give style using css().
  • Theme.js
export default {
  color: {
    ...
    default: '#999999',
  },
  size: {
    ...
    md: 14,
    ...
  },
  ...
};
Enter fullscreen mode Exit fullscreen mode
  1. Create 'Theme.js' file and export an object. The object should include property values commonly shown in the project overall.
import react, {Component} from 'React'
import withStyles, { css } from './withStyles';

class StyledComp extends Component {
    const { styles } = this.props;

    render(){
        return (<div ...css(styles.default)></div>)
    }

withStyles(({ color, size }) => ({
  default: {
    color: color.default,
    fontSize: size.md,
  },
}))(StyledComp);
Enter fullscreen mode Exit fullscreen mode
  1. withStyles() creates a function which takes Component as input and gives Component (with {default: ...} props) as output. Higher-Ordered Component is what takes WrappedComponent, modify its behavior(add lifecycle method, log its output, conditonally render, attach/detach eventListener and etc...) and returns modified Component.

Top comments (0)