Junior — Middle
What makes the use of CSS-in-JS popular among modern web developers?
sobes.tech AI
Answer from AI
CSS-in-JS is popular among modern web developers for several reasons:
- Localizing styles: Styles are written directly in components, reducing the likelihood of class name conflicts and simplifying maintenance.
- Dynamic styles: JavaScript can be used to compute styles on the fly based on props or state.
- Development convenience: Integration with component architecture (e.g., React) makes the code more modular and readable.
- Automatic dependency management: Some CSS-in-JS libraries automatically insert only the necessary styles into the DOM.
Example using styled-components in React:
import styled from 'styled-components';
const Button = styled.button`
background-color: ${props => props.primary ? 'blue' : 'gray'};
color: white;
padding: 10px;
`;
// Usage
<Button primary>Primary</Button>
<Button>Default</Button>