tips / javascript
Pass props to component in Emotion
January 26, 2023
Emotion is a library designed for writing css styles with JavaScript.
Let’s see how to pass props to a component in Emotion using css Prop.
Step 1: Install emotion
npm install @emotion/react
Step 2: Create Title component
I created Title component to display headlines.
Title component receives characters ( children
) and textAlign
as props.
import { ReactElement, ReactNode } from "react";
import { css } from "@emotion/react";
interface TitleProps {
children: ReactNode
textAlign?: string
}
export const Title = ({
title,
textAlign = "left"
}: TitleProps): ReactElement => {
return (
<h1 css={titleStyle}>
{children}
</h1>
);
};
const titleStyle = css`
font-size: 2.4rem;
font-weight: 700;
letter-spacing: 0.05em;
color: var(--color-primary);
`;
Step 3: Pass props to css Prop
Add props to a JSX element you want to pass props.
<h1 css={titleStyle({ textAlign })}>
Receive props in css Prop.
const titleStyle = ({ textAlign }: { textAlign: string }) => css`
font-size: 2.4rem;
font-weight: 700;
letter-spacing: 0.05em;
color: var(--color-primary);
text-align: ${textAlign};
`
Here’s component examples 🚀
{/* left-aligned (default) */}
<Title>Headline</Title>
{/* center-aligned */}
<Title textAlign="center">Headline</Title>
{/* right-aligned */}
<Title textAlign="right">Headline</Title>