How to style components with styled-components in React

Styling React components with CSS-in-JS provides component-scoped styles and dynamic styling capabilities that traditional CSS cannot easily achieve. As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development, I’ve explored various styling approaches and found styled-components to be particularly effective for component libraries. The most efficient approach is using the styled-components library, which creates styled React components with template literals and provides excellent TypeScript support. This method enables dynamic styling based on props while maintaining excellent performance and developer experience.

Install styled-components and create styled React components using template literals for dynamic, scoped styling.

import styled from 'styled-components'

const StyledButton = styled.button`
  background: ${props => props.primary ? '#007bff' : '#6c757d'};
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
`

function App() {
  return <StyledButton primary>Click me</StyledButton>
}

Styled-components creates actual React components that render specific HTML elements with attached styles. The template literal syntax allows you to write CSS directly while accessing props for dynamic styling. Styles are automatically scoped to the component, eliminating CSS conflicts. The library also supports advanced features like theme providers, CSS animations, and server-side rendering.

Best Practice Note:

This is similar to how we architect styling in CoreUI React components, though we primarily use SCSS for broader browser compatibility. Styled-components excels for component libraries that need heavily dynamic styling and tight integration with React props and state.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

How to limit items in a .map loop in JavaScript
How to limit items in a .map loop in JavaScript

How to loop through an array in JavaScript
How to loop through an array in JavaScript

Answers by CoreUI Core Team