Styled Components
Styled Components - это одно из самых популярных на сегодняшний день решений
CSS-in-JS
дляReact-приложений
.CSS-in-JS
позволяет писать стили прямо вJS
, кастомизировать их различными способами и использовать в виде обычныхReact-компонентов
.
Установка
yarn add styled-components
# или
npm i styled-components
Импорт
import styled, { createGlobalStyle, keyframes } from 'styled-components'
// styled - стилизация компонента
// createGlobalStyle - глобальные стили
// keyframes - анимация
Использование
Глобальные стили
const GlobalStyle = createGlobalStyle`
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
background: radial-gradient(yellow, orange);
display: grid;
place-content: center;
text-align: center;
}
`
Стилизация компонентов
const StyledComponent = styled.tagName`
prop: value;
`
// пример
const Button = styled.button`
margin: 0.5em;
padding: 0.5em 0;
width: 132px;
background: #f0f0f0;
outline: none;
border: none;
border-radius: 4px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.25);
font-family: Audiowide;
font-size: 1em;
letter-spacing: 2px;
text-transform: uppercase;
color: #1c1c1c;
cursor: pointer;
user-select: none;
`
Вложенность (по аналогии с SASS)
const StyledComponent = styled.tagName`
&:hover {
prop: value;
}
`
// пример
const Button = styled.button`
// ...
transition: 0.2s;
&:hover {
transform: scale(1.05);
}
&:active {
box-shadow: none;
}
`
Расширение стилей компонента с помощью пропов
const StyledComponent = styled.tagName`
prop: ${props => props.propName ? 'ifTrueValue' : 'ifFalseValue'};
`
// пример
const Button = styled.button`
// ...
background: ${(props) => (props.primary ? '#337ab7' : '#f0f0f0f')};
color: ${(props) => (props.primary ? '#f0f0f0' : '#1c1c1c')};
`
Расширение стилей базового компонента
const StyledComponent = styled(BaseStyledComponent)`
prop: value;
`
// пример
const SuccessButton = styled(Button)`
background: #5cb85c;
color: #f0f0f0;
`
Изменение пропов компонента
const StyledComponent = (props) => (
<WrappedStyledComponent {...props} children={props.children.methodName} />
)
// пример
const ReversedButton = (props) => (
<Button {...props} children={props.chidren.reverse()} />
)