Kurs JavaScript i React · Moduł 7: Stylowanie i animacje
Styled Components - Kosmiczna fuzja JSX i CSS
W tej lekcji10
W naszej kosmicznej podróży przez świat stylowania w React, docieramy do fascynującej technologii, która zaciera granice między kodem a stylem. Styled Components to jak zaawansowany statek międzygwiezdny, który łączy w sobie DNA dwóch światów - JavaScriptu i CSS - tworząc nową formę życia, idealnie dostosowaną do ekosystemu React.
Czym są Styled Components?
Styled Components to jedna z najpopularniejszych bibliotek CSS-in-JS, która pozwala na pisanie faktycznego CSS bezpośrednio w plikach JavaScript/JSX, jednocześnie tworząc normalne komponenty React. To rewolucyjne podejście do stylowania pozwala nam myśleć o naszych komponentach jako w pełni zamkniętych, autonomicznych jednostkach, gdzie zarówno logika, jak i styl są zebrane w jednym miejscu.
Wyobraź sobie komponenty jak moduły statku kosmicznego - każdy zawiera zarówno swoją funkcję (silniki, systemy podtrzymywania życia, nawigacja), jak i swój wygląd (panele sterowania, wskaźniki, interfejsy) - wszystko hermetycznie zamknięte w jednej, spójnej całości.
Instalacja i konfiguracja
Zanim rozpoczniemy naszą przygodę ze Styled Components, musimy zainstalować bibliotekę:
npm install styled-components
# lub
yarn add styled-components
# lub
pnpm add styled-componentsDla użytkowników TypeScript, warto dodać również typy:
npm install @types/styled-componentsPodstawy Styled Components
Tworzenie prostego komponentu stylizowanego
Tworzenie stylizowanych komponentów jest niezwykle intuicyjne. Wystarczy użyć funkcji styled zaimportowanej z biblioteki, a następnie nazwę tagu HTML, do którego chcemy aplikować style:
import styled from 'styled-components';
// Tworzenie stylizowanego przycisku
const Button = styled.button`
background-color: #4a90e2;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
&:hover {
background-color: #357ae8;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
&:active {
transform: translateY(1px);
}
`;
// Użycie komponentu
function App() {
return (
<div>
<h1>Centrum Dowodzenia</h1>
<Button>Uruchom procedurę startową</Button>
</div>
);
}W powyższym przykładzie stworzyliśmy stylizowany komponent Button, który działa jak normalny przycisk HTML, ale ma predefiniowane style. Zauważ charakterystyczną składnię z użyciem backticks (``), która pozwala na pisanie wieloliniowego CSS. Co więcej, możemy używać selektora & jak w Sass, aby odwoływać się do samego komponentu.
Dziedziczenie stylów
Możemy rozszerzać istniejące komponenty stylizowane, dodając do nich nowe style:
// Bazowy przycisk
const Button = styled.button`
padding: 10px 15px;
border: none;
border-radius: 4px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
`;
// Rozszerzenie bazowego przycisku
const PrimaryButton = styled(Button)`
background-color: #4a90e2;
color: white;
&:hover {
background-color: #357ae8;
}
`;
// Kolejne rozszerzenie
const DangerButton = styled(Button)`
background-color: #e74c3c;
color: white;
&:hover {
background-color: #c0392b;
}
`;Praca z props (parametrami)
Jedną z najpotężniejszych funkcji Styled Components jest możliwość dynamicznego stylowania w oparciu o propsy przekazywane do komponentu:
const Button = styled.button`
padding: 10px 15px;
border: none;
border-radius: 4px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
/* Dynamiczne kolory na podstawie props */
background-color: ${props =>
props.primary ? '#4a90e2' : props.danger ? '#e74c3c' : props.success ? '#2ecc71' : '#95a5a6'};
color: white;
/* Dynamiczny rozmiar */
font-size: ${props => (props.large ? '18px' : '14px')};
padding: ${props => (props.large ? '12px 20px' : '8px 12px')};
/* Zablokowany przycisk */
opacity: ${props => (props.disabled ? 0.5 : 1)};
cursor: ${props => (props.disabled ? 'not-allowed' : 'pointer')};
&:hover {
${props => !props.disabled && `
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
`}
}
`;
// Użycie z różnymi propsami
function ActionPanel() {
return (
<div>
<Button>Normalny</Button>
<Button primary>Podstawowy</Button>
<Button danger>Usuń</Button>
<Button success large>Zapisz</Button>
<Button disabled>Niedostępny</Button>
</div>
);
}W przykładzie powyżej, styl przycisku zmienia się w zależności od przekazanych propsów. Możemy przekazywać dowolne propsy do naszych stylizowanych komponentów, a następnie używać ich w wyrażeniach wewnątrz literałów szablonowych.
Prop-forwarding i atrybuty HTML
Styled Components automatycznie przekazują wszystkie nieużyte propsy do elementu DOM:
// Ten przycisk będzie miał typ "submit" i obsługę onClick
function FormSubmit() {
return (
<Button
type="submit"
onClick={() => console.log('Formularz wysłany!')}
>
Wyślij
</Button>
);
}Stylizacja istniejących komponentów
Możemy również stylizować istniejące komponenty React, o ile przyjmują one prop className:
// Zwykły komponent React
function CustomInput({ className, ...props }) {
return (
<input
className={className}
{...props}
/>
);
}
// Stylizacja istniejącego komponentu
const StyledCustomInput = styled(CustomInput)`
border: 2px solid #3498db;
border-radius: 4px;
padding: 8px 12px;
width: 100%;
font-size: 16px;
&:focus {
outline: none;
border-color: #2980b9;
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.3);
}
`;Zaawansowane funkcje Styled Components
Globalne style
Styled Components oferuje również komponent GlobalStyle do definiowania globalnych stylów:
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
/* Reset CSS */
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* Zmienne globalne */
:root {
--primary-color: #4a90e2;
--secondary-color: #8a2be2;
--success-color: #2ecc71;
--danger-color: #e74c3c;
--warning-color: #f1c40f;
--text-light: #ecf0f1;
--text-dark: #2c3e50;
--background-dark: #1a1a2e;
--background-light: #f5f5f5;
}
body {
font-family: 'Space Grotesk', sans-serif;
line-height: 1.6;
background-color: var(--background-dark);
color: var(--text-light);
}
a {
color: var(--primary-color);
text-decoration: none;
}
button {
font-family: inherit;
}
`;
// Użycie GlobalStyle w aplikacji
function App() {
return (
<>
<GlobalStyle />
<div>
{/* Zawartość aplikacji */}
</div>
</>
);
}Theming (tematyzacja)
Jedną z największych zalet Styled Components jest wsparcie dla tematów:
import { ThemeProvider } from 'styled-components';
// Definicja motywu
const darkTheme = {
colors: {
primary: '#4a90e2',
secondary: '#8a2be2',
success: '#2ecc71',
danger: '#e74c3c',
warning: '#f1c40f',
background: '#1a1a2e',
text: '#ecf0f1',
muted: '#95a5a6'
},
fonts: {
body: "'Space Grotesk', sans-serif",
heading: "'Nova Mono', monospace"
},
spacing: {
xs: '4px',
sm: '8px',
md: '16px',
lg: '24px',
xl: '32px'
},
borderRadius: {
small: '4px',
medium: '8px',
large: '12px',
round: '50%'
},
shadows: {
small: '0 2px 4px rgba(0, 0, 0, 0.1)',
medium: '0 4px 8px rgba(0, 0, 0, 0.2)',
large: '0 8px 16px rgba(0, 0, 0, 0.3)'
}
};
// Alternatywny motyw
const lightTheme = {
colors: {
primary: '#3498db',
secondary: '#9b59b6',
success: '#27ae60',
danger: '#c0392b',
warning: '#f39c12',
background: '#f5f5f5',
text: '#2c3e50',
muted: '#7f8c8d'
},
// Pozostałe właściwości takie same jak w darkTheme
fonts: darkTheme.fonts,
spacing: darkTheme.spacing,
borderRadius: darkTheme.borderRadius,
shadows: darkTheme.shadows
};
// Stylizowany komponent używający motywu
const Card = styled.div`
background-color: ${props =>
props.theme.colors.background === '#1a1a2e' ? '#252941' : '#ffffff'};
color: ${props => props.theme.colors.text};
border-radius: ${props => props.theme.borderRadius.medium};
padding: ${props => props.theme.spacing.md};
box-shadow: ${props => props.theme.shadows.small};
transition: all 0.3s ease;
&:hover {
box-shadow: ${props => props.theme.shadows.medium};
}
`;
// Stylizowany przycisk używający motywu
const Button = styled.button`
background-color: ${props => props.theme.colors.primary};
color: white;
padding: ${props => props.theme.spacing.sm} ${props => props.theme.spacing.md};
border: none;
border-radius: ${props => props.theme.borderRadius.small};
font-family: ${props => props.theme.fonts.body};
cursor: pointer;
&:hover {
background-color: ${props => {
const color = props.theme.colors.primary;
// Prostą funkcję ciemniejszego koloru
return color.replace(/rgb\((\d+), (\d+), (\d+)\)/, (_, r, g, b) =>
`rgb(${Math.max(0, r - 20)}, ${Math.max(0, g - 20)}, ${Math.max(0, b - 20)})`
);
}};
}
`;
// Użycie ThemeProvider i komponentów tematycznych
function App() {
const [darkMode, setDarkMode] = useState(true);
const theme = darkMode ? darkTheme : lightTheme;
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
<AppContainer>
<Header>
<h1>Kosmiczne Centrum Dowodzenia</h1>
<Button onClick={() => setDarkMode(!darkMode)}>
Przełącz tryb {darkMode ? "jasny" : "ciemny"}
</Button>
</Header>
<Card>
<h2>Panel Kontrolny</h2>
<p>Tutaj możesz zarządzać swoją kosmiczną misją.</p>
<Button>Uruchom</Button>
</Card>
</AppContainer>
</ThemeProvider>
);
}Animacje
Styled Components pozwala na łatwe tworzenie animacji z użyciem helper funkcji keyframes:
import styled, { keyframes } from 'styled-components';
// Definicja animacji
const pulse = keyframes`
0% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.8;
transform: scale(1.05);
}
100% {
opacity: 1;
transform: scale(1);
}
`;
const rotate = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
// Użycie animacji w komponencie
const PulsingButton = styled.button`
background-color: #e74c3c;
color: white;
padding: 12px 24px;
border: none;
border-radius: 4px;
font-weight: bold;
/* Aplikacja animacji */
animation: ${pulse} 2s infinite ease-in-out;
`;
const Spinner = styled.div`
width: 40px;
height: 40px;
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid #3498db;
border-radius: 50%;
/* Animacja rotacji */
animation: ${rotate} 1s linear infinite;
`;
// Animacje warunkowe
const AlertBadge = styled.span`
display: inline-block;
padding: 4px 8px;
background-color: red;
color: white;
border-radius: 10px;
font-size: 12px;
/* Animacja tylko gdy jest ważny alert */
animation: ${props => props.critical ?
css`${pulse} 1s infinite` : 'none'};
`;Pseudoelementy i pseudoklasy
Styled Components obsługują wszystkie pseudoelementy i pseudoklasy CSS:
const HoverCard = styled.div`
position: relative;
padding: 20px;
background-color: #252941;
border-radius: 8px;
transition: all 0.3s ease;
/* Pseudoklasy */
&:hover {
transform: translateY(-5px);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
}
&:active {
transform: translateY(-2px);
}
/* Pseudoelementy */
&::before {
content: "";
position: absolute;
top: -10px;
left: -10px;
right: -10px;
bottom: -10px;
border-radius: 12px;
background: linear-gradient(45deg, #4a90e2, #8a2be2);
z-index: -1;
opacity: 0;
transition: opacity 0.3s ease;
}
&:hover::before {
opacity: 1;
}
/* Zagnieżdżone selektory */
h3 {
margin-bottom: 10px;
color: #ecf0f1;
}
p {
color: #bdc3c7;
}
/* Złożone selektory */
&:hover h3 {
color: #4a90e2;
}
`;Media queries
Styled Components doskonale obsługuje media queries, umożliwiając tworzenie responsywnych komponentów:
const ResponsiveContainer = styled.div`
padding: 20px;
background-color: #252941;
border-radius: 8px;
/* Bazowa szerokość */
width: 100%;
/* Media queries */
@media (min-width: 768px) {
width: 750px;
margin: 0 auto;
}
@media (min-width: 992px) {
width: 970px;
}
@media (min-width: 1200px) {
width: 1170px;
}
/* Responsywne zmiany stylów */
h1 {
font-size: 24px;
@media (min-width: 768px) {
font-size: 32px;
}
}
/* Możemy używać media queries wewnątrz warunków */
display: ${props => props.hidden ?
`
none;
@media (min-width: 768px) {
display: block;
}
` : 'block'
};
`;Helpers i pomocnicze funkcje
Styled Components dostarcza kilka użytecznych narzędzi, jak css do wielokrotnego używania fragmentów stylu:
import styled, { css } from 'styled-components';
// Tworzenie reużywalnych fragmentów stylów
const flexCenter = css`
display: flex;
justify-content: center;
align-items: center;
`;
const buttonBase = css`
padding: 10px 15px;
border: none;
border-radius: 4px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
`;
const dangerStyles = css`
background-color: #e74c3c;
color: white;
&:hover {
background-color: #c0392b;
}
`;
// Użycie fragmentów w komponentach
const FlexContainer = styled.div`
${flexCenter}
gap: 20px;
flex-wrap: wrap;
`;
const Button = styled.button`
${buttonBase}
background-color: #4a90e2;
color: white;
&:hover {
background-color: #357ae8;
}
${props => props.danger && dangerStyles}
`;Zaawansowane wzorce i techniki
Reużywalne komponenty i ich wariacje
Jedną z najlepszych praktyk w Styled Components jest tworzenie reużywalnych komponentów bazowych z wariacjami:
// Bazowy komponent przycisku
const BaseButton = styled.button`
padding: 10px 15px;
border: none;
border-radius: 4px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
font-size: 14px;
`;
// Warianty przycisków
const PrimaryButton = styled(BaseButton)`
background-color: ${props => props.theme.colors.primary};
color: white;
&:hover {
background-color: ${props => darken(0.1, props.theme.colors.primary)};
}
`;
const SecondaryButton = styled(BaseButton)`
background-color: transparent;
color: ${props => props.theme.colors.primary};
border: 2px solid ${props => props.theme.colors.primary};
&:hover {
background-color: ${props => rgba(props.theme.colors.primary, 0.1)};
}
`;
const DangerButton = styled(BaseButton)`
background-color: ${props => props.theme.colors.danger};
color: white;
&:hover {
background-color: ${props => darken(0.1, props.theme.colors.danger)};
}
`;
// Rozmiary przycisków
const SmallButton = css`
padding: 6px 10px;
font-size: 12px;
`;
const LargeButton = css`
padding: 12px 20px;
font-size: 16px;
`;
// Komponent wyższego rzędu dla rozmiaru
const sizedButton = (Component) => styled(Component)`
${props => props.small && SmallButton}
${props => props.large && LargeButton}
`;
// Tworzenie wariantów z rozmiarami
const SizedPrimaryButton = sizedButton(PrimaryButton);
const SizedSecondaryButton = sizedButton(SecondaryButton);
const SizedDangerButton = sizedButton(DangerButton);
// Użycie
function ActionPanel() {
return (
<div>
<SizedPrimaryButton>Normalne</SizedPrimaryButton>
<SizedPrimaryButton small>Małe</SizedPrimaryButton>
<SizedPrimaryButton large>Duże</SizedPrimaryButton>
<SizedSecondaryButton>Normalne</SizedSecondaryButton>
<SizedDangerButton large>Duży alarm</SizedDangerButton>
</div>
);
}Pomysłowe wykorzystanie atrybutu as
Styled Components pozwala na zmianę elementu HTML używanego przez komponent za pomocą propsu as:
const Button = styled.button`
background-color: #4a90e2;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
font-weight: bold;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
text-decoration: none;
`;
function App() {
return (
<div>
<Button>Normalny przycisk</Button>
{/* Renderowanie jako link */}
<Button as="a" href="/destination">
Przycisk jako link
</Button>
{/* Renderowanie jako inny element */}
<Button as="div" role="button" tabIndex={0}>
Przycisk jako div
</Button>
{/* Możemy użyć innego komponentu React */}
<Button as={Link} to="/dashboard">
Przycisk jako router Link
</Button>
</div>
);
}Warunkowa stylizacja
Styled Components pozwala na bardzo szczegółową warunkową stylizację:
const AlertBox = styled.div`
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
display: flex;
align-items: center;
/* Zmiana koloru tła na podstawie typu alertu */
background-color: ${props =>
props.type === 'success' ? '#d4edda' :
props.type === 'danger' ? '#f8d7da' :
props.type === 'warning' ? '#fff3cd' :
props.type === 'info' ? '#d1ecf1' :
'#e2e3e5'
};
/* Zmiana koloru tekstu */
color: ${props =>
props.type === 'success' ? '#155724' :
props.type === 'danger' ? '#721c24' :
props.type === 'warning' ? '#856404' :
props.type === 'info' ? '#0c5460' :
'#383d41'
};
/* Zmiana obramowania */
border: 1px solid ${props =>
props.type === 'success' ? '#c3e6cb' :
props.type === 'danger' ? '#f5c6cb' :
props.type === 'warning' ? '#ffeeba' :
props.type === 'info' ? '#bee5eb' :
'#d6d8db'
};
/* Zmiana ikon */
&::before {
content: "${props =>
props.type === 'success' ? 'OK' :
props.type === 'danger' ? '×' :
props.type === 'warning' ? '!' :
props.type === 'info' ? 'ℹ' :
'ℹ'
}";
margin-right: 10px;
font-size: 18px;
}
/* Możemy również używać zagnieżdżonych warunków i funkcji */
${props => {
if (props.dismissable) {
return `
padding-right: 40px;
position: relative;
`;
}
}}
`;
// Przycisk zamknięcia dla odrzucalnych alertów
const CloseButton = styled.button`
position: absolute;
top: 10px;
right: 10px;
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: inherit;
opacity: 0.5;
&:hover {
opacity: 1;
}
`;
// Użycie komponentu
function Notifications() {
return (
<div>
<AlertBox type="success">
Misja zakończona powodzeniem!
</AlertBox>
<AlertBox type="danger" dismissable>
Uwaga: Wykryto awarię systemu!
<CloseButton>×</CloseButton>
</AlertBox>
<AlertBox type="warning">
Ostrzeżenie: Niski poziom paliwa.
</AlertBox>
<AlertBox type="info">
Informacja: Zbliżasz się do stacji kosmicznej.
</AlertBox>
</div>
);
}Praktyczny przykład: Kosmiczny Dashboard
Zobaczmy, jak można stworzyć bardziej złożony interfejs używając Styled Components:
import React, { useState } from 'react';
import styled, { ThemeProvider, createGlobalStyle, keyframes } from 'styled-components';
// ========== Theme Definition ==========
const theme = {
colors: {
primary: '#4a90e2',
secondary: '#8a2be2',
success: '#2ecc71',
danger: '#e74c3c',
warning: '#f1c40f',
info: '#3498db',
background: '#0f1429',
cardBg: '#1a1f3c',
text: '#ecf0f1',
textMuted: '#95a5a6',
border: '#2c3e50'
},
spacing: {
xs: '4px',
sm: '8px',
md: '16px',
lg: '24px',
xl: '32px'
},
fonts: {
body: "'Space Grotesk', sans-serif",
mono: "'JetBrains Mono', monospace"
},
borderRadius: {
sm: '4px',
md: '8px',
lg: '16px'
}
};
// ========== Global Style ==========
const GlobalStyle = createGlobalStyle`
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: ${props => props.theme.fonts.body};
background-color: ${props => props.theme.colors.background};
color: ${props => props.theme.colors.text};
line-height: 1.6;
}
h1, h2, h3, h4, h5, h6 {
margin-bottom: ${props => props.theme.spacing.md};
}
`;
// ========== Animations ==========
const fadeIn = keyframes`
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
`;
const pulse = keyframes`
0% {
transform: scale(1);
}
50% {
transform: scale(1.05);
}
100% {
transform: scale(1);
}
`;
const rotate = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
// ========== Layout Components ==========
const AppContainer = styled.div`
max-width: 1200px;
margin: 0 auto;
padding: ${props => props.theme.spacing.lg};
`;
const Header = styled.header`
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: ${props => props.theme.spacing.xl};
padding-bottom: ${props => props.theme.spacing.md};
border-bottom: 1px solid ${props => props.theme.colors.border};
animation: ${fadeIn} 0.5s ease-out forwards;
`;
const MainTitle = styled.h1`
color: ${props => props.theme.colors.primary};
font-size: 28px;
display: flex;
align-items: center;
&::before {
content: "▲";
margin-right: ${props => props.theme.spacing.sm};
}
`;
const Grid = styled.div`
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: ${props => props.theme.spacing.lg};
margin-bottom: ${props => props.theme.spacing.xl};
animation: ${fadeIn} 0.5s ease-out forwards;
animation-delay: 0.2s;
opacity: 0;
`;
const WideSection = styled.section`
grid-column: 1 / -1;
animation: ${fadeIn} 0.5s ease-out forwards;
animation-delay: 0.4s;
opacity: 0;
`;
// ========== Card Components ==========
const Card = styled.div`
background-color: ${props => props.theme.colors.cardBg};
border-radius: ${props => props.theme.borderRadius.md};
padding: ${props => props.theme.spacing.lg};
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
${props => props.interactive && `
cursor: pointer;
transition: all 0.3s ease;
&:hover {
transform: translateY(-5px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
}
`}
${props => props.primary && `
border-top: 4px solid ${props.theme.colors.primary};
`}
${props => props.warning && `
border-top: 4px solid ${props.theme.colors.warning};
`}
${props => props.danger && `
border-top: 4px solid ${props.theme.colors.danger};
`}
${props => props.success && `
border-top: 4px solid ${props.theme.colors.success};
`}
`;
const CardTitle = styled.h2`
font-size: 18px;
display: flex;
align-items: center;
margin-bottom: ${props => props.theme.spacing.md};
${props => props.icon && `
&::before {
content: "${props.icon}";
margin-right: ${props.theme.spacing.sm};
}
`}
`;
const CardContent = styled.div`
margin-bottom: ${props => props.theme.spacing.md};
`;
// ========== Button Components ==========
const Button = styled.button`
background-color: ${props =>
props.primary ? props.theme.colors.primary :
props.danger ? props.theme.colors.danger :
props.success ? props.theme.colors.success :
props.warning ? props.theme.colors.warning :
'#95a5a6'
};
color: white;
border: none;
border-radius: ${props => props.theme.borderRadius.sm};
padding: ${props => props.small ? '6px 12px' : '10px 20px'};
font-family: ${props => props.theme.fonts.body};
font-size: ${props => props.small ? '12px' : '14px'};
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
&:hover {
filter: brightness(1.1);
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
&:active {
transform: translateY(0);
}
${props => props.ghost && `
background-color: transparent;
color: ${
props.primary ? props.theme.colors.primary :
props.danger ? props.theme.colors.danger :
props.success ? props.theme.colors.success :
props.warning ? props.theme.colors.warning :
props.theme.colors.text
};
border: 1px solid currentColor;
&:hover {
background-color: rgba(255, 255, 255, 0.05);
}
`}
${props => props.icon && `
display: inline-flex;
align-items: center;
&::before {
content: "${props.icon}";
margin-right: 8px;
}
`}
${props => props.block && `
display: block;
width: 100%;
`}
${props => props.disabled && `
opacity: 0.5;
cursor: not-allowed;
pointer-events: none;
`}
& + & {
margin-left: ${props => props.theme.spacing.sm};
}
`;
// ========== Data Display Components ==========
const Statistic = styled.div`
text-align: center;
`;
const StatValue = styled.div`
font-size: 36px;
font-weight: bold;
color: ${props =>
props.primary
? props.theme.colors.primary
: props.danger
? props.theme.colors.danger
: props.success
? props.theme.colors.success
: props.warning
? props.theme.colors.warning
: props.theme.colors.text};
margin-bottom: ${props => props.theme.spacing.xs};
${props => props.pulse && `
animation: ${pulse} 2s infinite ease-in-out;
`}
`;
const StatLabel = styled.div`
font-size: 14px;
color: ${props => props.theme.colors.textMuted};
text-transform: uppercase;
`;
const ProgressBar = styled.div`
height: 8px;
background-color: rgba(0, 0, 0, 0.2);
border-radius: 4px;
overflow: hidden;
margin-bottom: ${props => props.theme.spacing.md};
&::after {
content: '';
display: block;
height: 100%;
width: ${props => `${props.value}%`};
background-color: ${props =>
props.primary
? props.theme.colors.primary
: props.danger
? props.theme.colors.danger
: props.success
? props.theme.colors.success
: props.warning
? props.theme.colors.warning
: props.theme.colors.primary};
transition: width 0.5s ease-in-out;
}
`;
const StatusIndicator = styled.span`
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: ${props => props.theme.spacing.sm};
background-color: ${props =>
props.status === 'online'
? props.theme.colors.success
: props.status === 'warning'
? props.theme.colors.warning
: props.status === 'critical'
? props.theme.colors.danger
: props.status === 'offline'
? '#95a5a6'
: props.theme.colors.info};
${props => props.status === 'online' && `
box-shadow: 0 0 10px ${props.theme.colors.success};
`}
${props => props.status === 'critical' && `
animation: ${pulse} 1s infinite;
`}
`;
// ========== Table Components ==========
const Table = styled.table`
width: 100%;
border-collapse: collapse;
`;
const TableHeader = styled.th`
text-align: left;
padding: ${props => props.theme.spacing.sm};
border-bottom: 2px solid ${props => props.theme.colors.border};
color: ${props => props.theme.colors.textMuted};
font-weight: 500;
`;
const TableCell = styled.td`
padding: ${props => props.theme.spacing.sm};
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
`;
const TableRow = styled.tr`
transition: background-color 0.2s ease;
&:hover {
background-color: rgba(255, 255, 255, 0.05);
}
`;
// ========== Loading Spinner ==========
const Spinner = styled.div`
display: inline-block;
width: 24px;
height: 24px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: ${props => props.theme.colors.primary};
animation: ${rotate} 1s linear infinite;
margin-right: ${props => props.theme.spacing.sm};
`;
// ========== Application Component ==========
function SpaceDashboard() {
const [systemStatus, setSystemStatus] = useState('online');
const [fuelLevel, setFuelLevel] = useState(72);
const [oxygenLevel, setOxygenLevel] = useState(93);
const [alerts, setAlerts] = useState([
{ id: 1, message: "Zmiana ciśnienia w module C", severity: "warning", time: "10:23" },
{ id: 2, message: "Aktualizacja nawigacji zainstalowana", severity: "info", time: "09:15" },
{ id: 3, message: "Cząsteczki mikrometeoroidów wykryte", severity: "warning", time: "07:42" },
]);
const crewMembers = [
{ id: 1, name: "Alex Chen", role: "Kapitan", status: "Mostek", avatar: "" },
{ id: 2, name: "Maria Rodriguez", role: "Inżynier", status: "Maszynownia", avatar: "" },
{ id: 3, name: "Jackson Lee", role: "Nawigator", status: "Mostek", avatar: "" },
{ id: 4, name: "Sophia Kim", role: "Lekarz", status: "Laboratorium", avatar: "" },
];
const toggleSystemStatus = () => {
setSystemStatus(systemStatus === 'online' ? 'warning' : 'online');
};
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
<AppContainer>
<Header>
<MainTitle>Kosmiczne Centrum Dowodzenia</MainTitle>
<div>
<Button primary icon="▲" onClick={toggleSystemStatus}>
System {systemStatus === 'online' ? 'Online' : 'Uwaga'}
</Button>
</div>
</Header>
<Grid>
{/* System Status Card */}
<Card primary>
<CardTitle icon="◆">Status Systemów</CardTitle>
<CardContent>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px' }}>
<div>
<StatusIndicator status={systemStatus} />
Status główny: {
systemStatus === 'online' ? 'Wszystkie systemy sprawne' :
systemStatus === 'warning' ? 'Uwaga - sprawdź alerty' :
'Usterka'
}
</div>
</div>
<div>
<div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
<span>Poziom paliwa</span>
<span>{fuelLevel}%</span>
</div>
<ProgressBar
value={fuelLevel}
warning={fuelLevel < 50}
danger={fuelLevel < 20}
success={fuelLevel >= 50}
/>
<div style={{ marginBottom: '8px', display: 'flex', justifyContent: 'space-between' }}>
<span>Poziom tlenu</span>
<span>{oxygenLevel}%</span>
</div>
<ProgressBar
value={oxygenLevel}
warning={oxygenLevel < 70}
danger={oxygenLevel < 40}
success={oxygenLevel >= 70}
/>
</div>
</CardContent>
<Button ghost primary block>Szczegółowe statystyki</Button>
</Card>
{/* Crew Status Card */}
<Card success>
<CardTitle icon="◆">Status Załogi</CardTitle>
<CardContent>
<Table>
<thead>
<tr>
<TableHeader></TableHeader>
<TableHeader>Imię</TableHeader>
<TableHeader>Lokalizacja</TableHeader>
</tr>
</thead>
<tbody>
{crewMembers.map(member => (
<TableRow key={member.id}>
<TableCell>{member.avatar}</TableCell>
<TableCell>
{member.name}
<div style={{ fontSize: '12px', color: theme.colors.textMuted }}>
{member.role}
</div>
</TableCell>
<TableCell>{member.status}</TableCell>
</TableRow>
))}
</tbody>
</Table>
</CardContent>
<Button ghost success block>Zarządzaj załogą</Button>
</Card>
{/* Statistics Card */}
<Card>
<CardTitle icon="◆">Statystyki</CardTitle>
<CardContent>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<Statistic>
<StatValue primary>26</StatValue>
<StatLabel>Dni w kosmosie</StatLabel>
</Statistic>
<Statistic>
<StatValue success>97%</StatValue>
<StatLabel>Wydajność</StatLabel>
</Statistic>
<Statistic>
<StatValue warning pulse={fuelLevel < 30}>{fuelLevel}%</StatValue>
<StatLabel>Poziom paliwa</StatLabel>
</Statistic>
</div>
</CardContent>
<Button ghost block>Zobacz więcej</Button>
</Card>
{/* Alerts Card */}
<Card warning={alerts.length > 0}>
<CardTitle icon="!">Alerty</CardTitle>
<CardContent>
{alerts.length === 0 ? (
<div style={{ textAlign: 'center', padding: '20px 0', color: theme.colors.textMuted }}>
Brak aktywnych alertów
</div>
) : (
<div>
{alerts.map(alert => (
<div key={alert.id} style={{
marginBottom: '8px',
padding: '8px',
borderRadius: '4px',
backgroundColor: 'rgba(0, 0, 0, 0.2)'
}}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div>
<StatusIndicator status={
alert.severity === 'critical' ? 'critical' :
alert.severity === 'warning' ? 'warning' :
'online'
} />
{alert.message}
</div>
<div style={{ fontSize: '12px', color: theme.colors.textMuted }}>
{alert.time}
</div>
</div>
</div>
))}
</div>
)}
</CardContent>
<Button ghost warning block>Sprawdź wszystkie alerty</Button>
</Card>
</Grid>
<WideSection>
<Card>
<CardTitle>Panel Kontrolny Misji</CardTitle>
<CardContent>
<div style={{ display: 'flex', gap: '16px', marginBottom: '20px' }}>
<Button primary icon="▲">Rozpocznij Operację</Button>
<Button icon="◆">Analizuj Dane</Button>
<Button warning icon="!">System Diagnostyczny</Button>
<Button danger icon="×">Procedura Awaryjna</Button>
</div>
<div style={{
backgroundColor: 'rgba(0, 0, 0, 0.3)',
padding: '16px',
borderRadius: '8px',
fontFamily: theme.fonts.mono,
fontSize: '14px'
}}>
<div style={{ marginBottom: '8px' }}>
<span style={{ color: theme.colors.success }}>system$</span> Inicjalizacja systemów głównych...
</div>
<div style={{ marginBottom: '8px' }}>
<span style={{ color: theme.colors.success }}>system$</span> Sprawdzanie statusu komunikacji...
</div>
<div style={{ marginBottom: '8px' }}>
<span style={{ color: theme.colors.success }}>system$</span> Łączenie z satelitami...
</div>
<div>
<Spinner /> Oczekiwanie na dalsze instrukcje...
</div>
</div>
</CardContent>
</Card>
</WideSection>
</AppContainer>
</ThemeProvider>
);
}
export default SpaceDashboard;Dobrze przemyślane rozwiązanie: Biblioteka komponentów
Jednym z najlepszych podejść do zarządzania stylami w większych projektach React jest stworzenie własnej biblioteki komponentów:
// Plik: src/components/Button/Button.styles.js
import styled, { css } from 'styled-components';
// Reużywalne style
const buttonSizes = {
small: css`
padding: 6px 12px;
font-size: 12px;
`,
medium: css`
padding: 8px 16px;
font-size: 14px;
`,
large: css`
padding: 12px 20px;
font-size: 16px;
`
};
const buttonVariants = {
primary: css`
background-color: ${props => props.theme.colors.primary};
color: white;
&:hover {
background-color: ${props => props.theme.colors.primaryDark};
}
`,
secondary: css`
background-color: ${props => props.theme.colors.secondary};
color: white;
&:hover {
background-color: ${props => props.theme.colors.secondaryDark};
}
`,
success: css`
background-color: ${props => props.theme.colors.success};
color: white;
&:hover {
background-color: ${props => props.theme.colors.successDark};
}
`,
danger: css`
background-color: ${props => props.theme.colors.danger};
color: white;
&:hover {
background-color: ${props => props.theme.colors.dangerDark};
}
`
};
// Główny komponent przycisk
export const StyledButton = styled.button`
display: inline-flex;
align-items: center;
justify-content: center;
border: none;
border-radius: ${props => props.theme.borderRadius.sm};
font-family: ${props => props.theme.fonts.body};
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
// Domyślny rozmiar
${buttonSizes.medium}
// Zastosuj wybrany rozmiar
${props => props.size && buttonSizes[props.size]}
// Domyślny wariant
background-color: #e0e0e0;
color: #333;
&:hover {
background-color: #d5d5d5;
}
// Zastosuj wybrany wariant
${props => props.variant && buttonVariants[props.variant]}
// Ghost button style
${props => props.ghost && css`
background-color: transparent;
border: 1px solid currentColor;
&:hover {
background-color: rgba(0, 0, 0, 0.05);
}
`}
// Disabled state
${props => props.disabled && css`
opacity: 0.6;
cursor: not-allowed;
pointer-events: none;
`}
// Full width button
${props => props.fullWidth && css`
width: 100%;
`}
// Icon support
${props => props.iconPosition === 'left' && props.icon && css`
svg, img {
margin-right: 8px;
}
`}
${props => props.iconPosition === 'right' && props.icon && css`
svg, img {
margin-left: 8px;
}
`}
// Loading state
${props => props.loading && css`
position: relative;
color: transparent;
&::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
width: 18px;
height: 18px;
margin: -9px 0 0 -9px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: buttonLoader 0.8s linear infinite;
}
@keyframes buttonLoader {
to { transform: rotate(360deg); }
}
`}
`;
// Plik: src/components/Button/Button.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { StyledButton } from './Button.styles';
const Button = ({
children,
variant,
size,
disabled,
fullWidth,
ghost,
loading,
icon,
iconPosition = 'left',
as,
...props
}) => {
return (
<StyledButton
variant={variant}
size={size}
disabled={disabled || loading}
fullWidth={fullWidth}
ghost={ghost}
loading={loading}
icon={icon}
iconPosition={iconPosition}
as={as}
{...props}
>
{iconPosition === 'left' && icon}
{children}
{iconPosition === 'right' && icon}
</StyledButton>
);
};
Button.propTypes = {
children: PropTypes.node.isRequired,
variant: PropTypes.oneOf(['primary', 'secondary', 'success', 'danger']),
size: PropTypes.oneOf(['small', 'medium', 'large']),
disabled: PropTypes.bool,
fullWidth: PropTypes.bool,
ghost: PropTypes.bool,
loading: PropTypes.bool,
icon: PropTypes.node,
iconPosition: PropTypes.oneOf(['left', 'right']),
as: PropTypes.elementType
};
export default Button;
// Plik: src/components/index.js
export { default as Button } from './Button/Button';
export { default as Card } from './Card/Card';
// Inne eksporty...
// Użycie biblioteki komponentów
import { Button, Card } from './components';
function App() {
return (
<div>
<Card title="Panel sterowania">
<Button variant="primary" size="large">
Rozpocznij misję
</Button>
<Button variant="danger" ghost>
Anuluj
</Button>
</Card>
</div>
);
}Porównanie z innymi podejściami do stylowania
| Podejście | Zalety | Wady |
|---|---|---|
| Styled Components | - Prawdziwy CSS w JS<br>- Izolacja stylów<br>- Dynamiczne style oparte na propsach<br>- Gotowe wsparcie dla tematyzacji | - Zwiększa rozmiar paczki JS<br>- Krzywa uczenia dla nowych deweloperów<br>- Style są renderowane w czasie rzeczywistym |
| CSS Modules | - Lokalne zakresy CSS<br>- Brak runtime CSS-in-JS<br>- Znajoma składnia CSS | - Ograniczone dynamiczne style<br>- Trudniejsze warunkowe style<br>- Wymaga odpowiedniej konfiguracji narzędzi |
| SCSS/SASS | - Potężne funkcje (zmienne, mixiny, itd.)<br>- Kompilowane podczas budowania<br>- Znajoma składnia | - Nie ma izolacji selektorów<br>- Trudniejsza integracja z propsami<br>- Wymaga dodatkowych narzędzi |
| Tailwind CSS | - Szybki development<br>- Nie trzeba nazywać klas<br>- Spójny design system | - Rozdęte klasy HTML<br>- Utrudniona kustomizacja<br>- Stroma krzywa początkowej nauki |
Najlepsze praktyki i ograniczenia
Najlepsze praktyki
- Twórz reużywalne komponenty styli - unikaj powtarzania kodu CSS
- Używaj tematów - centralizuj wartości kolorów, odstępów, fontów itp.
- Unikaj zagnieżdżania - głębokie zagnieżdżanie może prowadzić do problemów z wydajnością
- Stosuj semantyczne nazewnictwo - nazwy komponentów powinny odzwierciedlać ich funkcję
- Wykorzystuj propsy dla wariantów - zamiast tworzyć oddzielne komponenty
Ograniczenia i pułapki
- Wydajność - przy dużej liczbie stylizowanych komponentów może wpływać na czas renderowania
- Server-Side Rendering - wymaga specjalnej konfiguracji dla SSR
- Krzywa uczenia - nowi deweloperzy muszą przyzwyczaić się do nowego paradygmatu
- Debugowanie - nazwy klas generowane automatycznie mogą utrudniać debugowanie
Podsumowanie
Styled Components to potężne narzędzie, które zmienia podejście do stylowania w React, umożliwiając bardziej komponentowe, modułowe i reaktywne interfejsy użytkownika. Dzięki możliwości pisania prawdziwego CSS bezpośrednio w komponentach, dynamicznego reagowania na propsy oraz łatwej tematyzacji, można tworzyć elastyczne i łatwe w utrzymaniu systemy komponentów UI.
W świecie kosmicznej eksploracji Reacta, Styled Components jest jak zaawansowany skafander kosmiczny - łączy w sobie wszystkie niezbędne narzędzia do przetrwania, jednocześnie oferując swobodę ruchu i komfort. Uczy nas, że logika i wygląd nie muszą być oddzielnymi bytami, a mogą ewoluować razem, tworząc nową jakość interfejsów użytkownika.
Kod do tej lekcji: App.jsx
import React, { useState } from 'react';
import styles from './SpaceStation.module.css';
// Demonstracja CSS Modules
function SpaceStation() {
const [activeModule, setActiveModule] = useState(null);
const modules = [
{ id: 1, name: 'Moduł Dowodzenia', status: 'online', type: 'command' },
{ id: 2, name: 'Moduł Naukowy', status: 'online', type: 'science' },
{ id: 3, name: 'Moduł Mieszkalny', status: 'online', type: 'habitat' },
{ id: 4, name: 'Moduł Energetyczny', status: 'warning', type: 'power' },
{ id: 5, name: 'Moduł Dokowania', status: 'offline', type: 'docking' }
];
const getStatusClass = (status) => {
switch(status) {
case 'online': return styles.statusOnline;
case 'warning': return styles.statusWarning;
case 'offline': return styles.statusOffline;
default: return '';
}
};
return (
<div className={styles.station}>
<header className={styles.header}>
<h1 className={styles.title}>Stacja Kosmiczna Orion</h1>
<p className={styles.subtitle}>System zarządzania modułami</p>
</header>
<div className={styles.dashboard}>
<div className={styles.moduleList}>
<h2 className={styles.sectionTitle}>Moduły stacji</h2>
{modules.map(module => (
<div
key={module.id}
className={`${styles.moduleCard} ${activeModule === module.id ? styles.active : ''}`}
onClick={() => setActiveModule(module.id)}
>
<div className={styles.moduleHeader}>
<span className={styles.moduleName}>{module.name}</span>
<span className={`${styles.status} ${getStatusClass(module.status)}`}>
{module.status}
</span>
</div>
<div className={styles.moduleInfo}>
<span className={styles.moduleType}>Typ: {module.type}</span>
</div>
</div>
))}
</div>
<div className={styles.details}>
<h2 className={styles.sectionTitle}>Panel szczegółów</h2>
{activeModule ? (
<div className={styles.detailsContent}>
<p>Wybrany moduł: <strong>{modules.find(m => m.id === activeModule)?.name}</strong></p>
<p>Status systemów: wszystkie systemy działają prawidłowo</p>
<div className={styles.actions}>
<button className={styles.buttonPrimary}>Diagnostyka</button>
<button className={styles.buttonSecondary}>Raport</button>
</div>
</div>
) : (
<p className={styles.placeholder}>Wybierz moduł z listy, aby zobaczyć szczegóły</p>
)}
</div>
</div>
<footer className={styles.footer}>
<p>CSS Modules zapewniają lokalne scope dla klas CSS</p>
</footer>
</div>
);
}
export default SpaceStation;Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jak przekazać dynamiczne wartości do styled-components na podstawie propsów?
2. Do czego służy ThemeProvider w styled-components?
Zadania praktyczne w grze
- Układanie w poziomie
Ułóż składnię tworzenia styled-component:
- Edytor kodu
Styled Components - podstawy tworzenia komponentów ze stylami w JavaScript
- Układanie w pionie
Uporządkuj kroki dodawania dynamicznych styli w styled-components:
- Edytor kodu
Styled Components ThemeProvider - system motywów z dynamicznym przełączaniem dark/light mode
- Układanie w poziomie
Ułóż poprawną składnię styled-component z dynamicznym kolorem:
- Układanie w pionie
Uporządkuj metody stylowania od najsłabszego do najsilniejszego powiązania z komponentem:
Zadania po tej lekcji
- Ułóż w kolejnościPodstawy: Składnia styled-components
- PytaniePodstawy: Dynamiczne style w styled-components
- Zadanie z kodemPodstawy: Praktyka: Styled Components
- Ułóż w kolejnościPodstawy: Proces dynamicznego stylowania w styled-components
- PytaniePodstawy: ThemeProvider w styled-components
- Zadanie z kodemPodstawy: Praktyka: ThemeProvider
- Ułóż w kolejnościPodstawy: Składnia styled-component z props
- Ułóż w kolejnościPodstawy: Zalety CSS-in-JS