React Component Styling

The official Bit React environments support CSS Modules using Less, CSS or SCSS, or CSS-in-JS styling using native or community libraries.

CSS modules

CSS modules are useful for components, as styles are encapsulated properly. Use the *.module.* pattern to scope your component names so as to avoid naming collisions.

For example, consider the following stylesheet named card.module.css:

.purpleCard {
  background: #8d2ee6;
}
CopiedCopy

Unlike regular style imports, style modules are imported into a named variable:

import styles from './card.module.css';

export function Card({ children }) {
  return <div className={styles.purpleCard}>{children}</div>;
}
CopiedCopy

SCSS

To use SCSS for styling, add a file named card.scss:

.purple-card {
  background: #8d2ee6;
}
CopiedCopy

Use the SCSS file as a module from your React component:

import './card.scss';

export function Card({ children }) {
  return <div className="purple-card">{children}</div>;
}
CopiedCopy

LESS

To use Less for styling, add a file named card.less to your component with the following content:

.purple-card {
  background: #8d2ee6;
}
CopiedCopy

Use the .less file as a module from your React component:

import './card.less';

export function Card({ children }) {
  return <div className="purple-card">{children}</div>;
}
CopiedCopy

CSS

You can also include global CSS in your components. Keep in mind that global styles might cause side effects in other components.

To add global CSS, create the file card.css in your component:

.purple-card {
  background: #8d2ee6;
}
CopiedCopy

Import the CSS file to one of your component's JS files like so:

import './card.css';

export function Card({ children }) {
  return <div className="purple-card">{children}</div>;
}
CopiedCopy

CSS-in-JS

Inline styling

The simplest CSS-in-JS solution is standard inline styling:

export function Card({ children }) {
  return (
    <div style={{ backgroundColor: '#818181' }}>
      <div>{children}</div>
    </div>
  );
}
CopiedCopy
`styled-components` should be configured as a peer dependency. Configure it in your `env.jsonc`.
CopiedCopy

styled-components

styled-components can be used by installing the library:

$bit
Copiedcopy

Use it in your components:

import styled from 'styled-components';

const StyledCard = styled.div`
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  &:hover {
    box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  }
`;

export function Card({ children }) {
  return (
    <StyledCard style={{ backgroundColor: '#818181' }}>
      <div>{children}</div>
    </StyledCard>
  );
}
CopiedCopy

Tailwind CSS

To use Tailwind, configure the Tailwind CSS Webpack Transformer to enable Tailwind CSS support for your component previews and app bundles.