Lesson 43 of 50
cssCSS‑in‑JS (Styled‑Components, Emotion)
9 mins
Course progress86%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 43 of 50
css9 mins
Keep these ideas in mind as you work through the lesson.
CSS‑in‑JS moves styling inside JavaScript, allowing styles to be parameterised by component props and enabling automatic scoping.
import styled from 'styled-components';
const Button = styled.button`
background:${props => props.primary ? '#0066cc' : '#ccc'};
color:#fff; padding:0.5rem 1rem; border:none;
border-radius:4px;
&:hover { opacity:0.9; }
`;
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
function Card({title, children}) {
return (
<section css={css`
background:#fff; border:1px solid #e0e0e0; padding:1rem;
box-shadow:${'0 2px 4px rgba(0,0,0,0.1)'};
`}>
<h2>{title}</h2>{children}
</section>
);
}
<StyleSheet> component to inject critical CSS into the HTML.css prop syntax.import { ThemeProvider } from 'styled-components';
const theme = { primary:'#0066cc', danger:'#c00' };
<ThemeProvider theme={theme}> <App/> </ThemeProvider>
Inside any styled component:
background:${props => props.theme.primary};
shouldForwardPropBy default, every prop is passed to the DOM element, which can cause warnings. Filter them:
const Button = styled('button', { shouldForwardProp: prop => prop !== 'primary' })`
background:${p=>p.primary?'#0066cc':'#ccc'};
`;
:focus-visible works the same inside styled components.styled-components, the generated stylesheet is placed after the main CSS, so make sure you don’t unintentionally override critical rules.