CSS Components logo

Full Component Example

A full example of a component using CSS Components.

Below is a full example of a basic component put together using CSS Components.

A component will be split into 3 files:

1src
2└── components
3    └── Panel
4        ├── index.tsx # The main component file
5        ├── styles.module.css # The CSS file
6        └── styles.tsx # The CSS Components file)
7

We are going to create a simple Panel component that has a title and some content. The component will have a wide prop that will make the panel fill the width of its container.

Here you can see the Panel component in action.

Hello World

This is some example content. It's not very exciting.

1import Panel from "@/components/Panel";
2
3() => (
4  <Panel title="Hello World" wide>
5    <p>This is some example content. It's not very exciting.</p>
6  </Panel>
7);
8

panel/index.tsx

This is the main component file. It's a simple component that has a title and some content. PanelWrapper, Title and Content are all CSS Components that are imported from styles.tsx.

Notice how this component is free of ugly CSS class names. Everything is symantec.

1import { PanelWrapper, Title, Content } from "./styles";
2
3interface Props {
4  title: string;
5  children: React.ReactNode;
6  wide?: boolean;
7}
8
9const Panel = ({ title, children, wide }: Props) => (
10  <PanelWrapper wide={wide}>
11    <Title>{title}</Title>
12    <Content>{children}</Content>
13  </PanelWrapper>
14);
15
16export default Panel;
17

panel/styles.tsx

This is the styles file. It contains the CSS Components that are used in the main component file. As you can see, CSS Components are simply a way to map CSS classes to React component in a logical way, nothing more.

1import { styled } from "@phntms/css-components";
2
3import css from "./styles.module.css";
4
5export const PanelWrapper = styled("div", {
6  css: css.PanelWrapper,
7  variants: {
8    wide: {
9      true: css.PanelWrapper_wide,
10    },
11  },
12});
13
14export const Title = styled("h2", {
15  css: css.Title,
16});
17
18export const Content = styled("section", {
19  css: css.Content,
20});
21

Please note that while this example employs standard CSS, you have the freedom to utilize any styling solution of your choice, such as SCSS.

panel/styles.module.css

Lastly, this is the bog standard CSS file. It contains the CSS classes that are used in the CSS Components.

1.PanelWrapper {
2  display: flex;
3  flex-direction: column;
4  text-align: center;
5  margin: auto;
6  width: 240px;
7  border-radius: 0.5rem;
8  overflow: hidden;
9  background-color: #e6e6e6;
10  color: black;
11}
12
13.PanelWrapper_wide {
14  width: 100%;
15}
16
17h2.Title {
18  background-color: #d6d6d6;
19  margin: 0;
20  padding: 1rem;
21}
22
23section.Content {
24  padding: 1rem;
25}
26