Styled components Material UI styled components Material UI css Import styles inside component
- Keeps track of which components are rendered on a page and injects their styles and nothing else
- Generate unique class names for components
- Dynamic styling (props)
- Automatic vendor prefixing
Note: Higly recommended to use Babel Plugin. See official doc for more details
// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
font-size: ${props => props.big || "1em"};
text-align: center;
color: palevioletred;
`;
// Extending
const CustomTitle = styled(Title)`
//...
`
In some cases you might want to change which tag or component a styled component renders. This is common when building a navigation bar for example, where there are a mix of anchor links and buttons but they should be styled identically.
You can use polymorhic "as" props
They use prepr-r stylish
const Thing = styled.div.attrs((/* props */) => ({ tabIndex: 0 }))`
&:hover {
color: red; // <Thing> when hovered
}
.something-else & {
border: 1px solid; // <Thing> inside another element labeled ".something-else"
}
`
const Input = styled.input.attrs(props => ({
// we can define static props
type: "password",
// or we can define dynamic ones
size: props.size || "1em",
}))`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
/* here we use the dynamically computed prop */
margin: ${props => props.size};
padding: ${props => props.size};
`;
CSS animations with @keyframes aren't scoped to a single component.
Note: export a keyframes helper which will generate a unique instance that you can use throughout your app: Note: keyframe is not supported by React Native. Use ReactNative.AnimatedAPI
All shared style fragment should use css helper!
const rotate = keyframes``
// ❌ This will throw an error!
const styles = `
animation: ${rotate} 2s linear infinite;
`;
// ✅ This will work as intended
const styles = css`
animation: ${rotate} 2s linear infinite;
`
For RN use css-to-react-native