Installation

To use styled components syntax, install @emotion/styled package:

yarn add @emotion/styled
npm install @emotion/styled

!important You will need to wrap your application with MantineProvider to access theme in styles.

import { MantineProvider } from '@mantine/core';
function App() {
return (
<div>
Wrap your app with MantineProvider, it is required if you want to access theme in styles.
</div>
);
}
function Demo() {
return (
<MantineProvider withGlobalStyles withNormalizeCSS>
<App />
</MantineProvider>
);
}

Usage

You can find @emotion/styled documentation here. All features are supported, and you get Mantine theme as an argument:

Styled component
import styled from '@emotion/styled';
const StyledComponent = styled.div`
text-align: center;
background-color: ${({ theme }) =>
theme.colorScheme === 'dark' ? theme.colors.dark[6] : theme.colors.gray[0]};
padding: 1.875rem;
border-radius: 0.3125rem;
cursor: pointer;
&:hover {
background-color: ${({ theme }) =>
theme.colorScheme === 'dark' ? theme.colors.dark[5] : theme.colors.gray[1]};
}
`;
function Demo() {
return <StyledComponent />;
}

Styles API

Use static selectors to access component Styles API:

import { Slider } from '@mantine/core';
import styled from '@emotion/styled';
const StyledSlider = styled(Slider)`
& .mantine-Slider-bar {
background-color: pink;
}
& .mantine-Slider-thumb {
border-color: pink;
background-color: white;
width: 1.5rem;
height: 1.5rem;
}
`;
function Demo() {
return <StyledSlider defaultValue={40} />;
}

TypeScript

Add theme type

Add emotion.d.ts declaration file to your src folder or to any place included in your tsconfig.json:

import '@emotion/react';
import type { MantineTheme } from '@mantine/core';
declare module '@emotion/react' {
export interface Theme extends MantineTheme {}
}

Polymorphic components

Emotion cannot correctly extract prop types from polymorphic components. To add styles to such components with @emotion/styled, you will need to redefine polymorphic component type with createPolymorphicComponent function:

import { Button, ButtonProps, createPolymorphicComponent } from '@mantine/core';
import styled from '@emotion/styled';
const _StyledButton = styled(Button)`
border-width: 0.125rem;
color: ${({ theme }) => (theme.colorScheme === 'dark' ? theme.white : theme.black)};
`;
const StyledButton = createPolymorphicComponent<'button', ButtonProps>(_StyledButton);
function Demo() {
return (
<StyledButton variant="outline" color="gray" radius="md">
This is styled button
</StyledButton>
);
}