Introduction
CSS-in-JS allows developers to write CSS directly within JavaScript, improving component reusability and styling management in modern frameworks like React.
1. What is Styled Components?
Styled Components is a popular library for CSS-in-JS, enabling dynamic styling within React components.
Installation
npm install styled-components
Bash2. Creating Styled Components
Define styles within JavaScript files using the styled
API.
import styled from 'styled-components';
const Button = styled.button`
background: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
&:hover {
background: darkblue;
}
`;
function App() {
return <Button>Click Me</Button>;
}
export default App;
JavaScript3. Passing Props for Dynamic Styling
Styled components allow props for conditional styling.
const Button = styled.button`
background: ${props => props.primary ? 'blue' : 'gray'};
color: white;
`;
<Button primary>Primary Button</Button>
JavaScript4. Theming with Styled Components
Define a theme and use it across components.
import { ThemeProvider } from 'styled-components';
const theme = {
primaryColor: "blue",
secondaryColor: "gray"
};
const Button = styled.button`
background: ${props => props.theme.primaryColor};
color: white;
`;
function App() {
return (
<ThemeProvider theme={theme}>
<Button>Theme Button</Button>
</ThemeProvider>
);
}
export default App;
JavaScriptConclusion
Styled Components provide a modern way to manage styles in React applications, enhancing maintainability and scalability.