Skip to main content

Emotion Styled Components

Our preferred method of styling components is through Emotion Styled components, which allows us to style our components with simple and readable vanilla CSS inside our JSX / TSX files, without needlessly complicating the syntax.

Styling a component#

To style our component we can use the styled() function from @emotion/styled (you need to have @emotion/styled and @emotion/react as dependencies).

import styled from "@emotion/styled";import { Typography, TypographyProps } from '@material-ui/core';
export interface IExampleProps extends Omit<TypographyProps, 'children'> {  text?: string;}
// Between the backticks you can write CSSconst StyledTypography = styled(Typography)`  line-height: 1rem;  font-size: 14pt;`;
const Example = ({ text = '' }: IExampleProps) => (  <StyledTypography>{text}</StyledTypography>);
export default Example;

You can also pass props into the CSS between the backticks like so:

import styled from "@emotion/styled";import { Typography, TypographyProps } from '@material-ui/core';
export interface IExampleProps extends Omit<TypographyProps, 'children'> {  bold?: boolean;  text?: string;}
const StyledTypography = styled(  ({ bold, ...props }: Omit<IExampleProps, "text">) => (    <Typography {...props} />  ))`  line-height: 1rem;  ${({ bold }) => `    font-size: ${bold ? "20pt" : "14pt"} !important;    font-weight: ${bold ? "bold" : "normal"} !important;  `}`;
const Example = ({ bold, text = '', ...props }: IExampleProps) => (  <StyledTypography bold={bold} {...props}>{text}</StyledTypography>);
export default Example;