DEV Community

Niraj Narkhede
Niraj Narkhede

Posted on

How React Styled Components works

Introduction: Styling Your React Apps with Ease

Hey there, fellow React UI developer! Are you tired of wrestling with CSS files and class names in your React projects? Well, I've got some great news for you. Today, we're diving into the world of React Styled Components -- a game-changer in how we style our React applications.

Styled Components allow us to write CSS directly in our JavaScript files, making our styling more modular, reusable, and easier to manage. It's like having your cake and eating it too -- you get all the power of CSS with the flexibility of JavaScript. Sounds exciting, right? Let's roll up our sleeves and get started with this step-by-step tutorial on React Styled Components.

Getting Started with React Styled Components

Setting Up Your Project

Before we jump into the styling goodness, let's make sure we have everything set up correctly. If you already have a React project, that's great! If not, you can create a new one using Create React App:

npx create-react-app my-styled-app
cd my-styled-app
Enter fullscreen mode Exit fullscreen mode

Now, let's install the Styled Components package:

npm install styled-components
Enter fullscreen mode Exit fullscreen mode

Great! We're all set to start styling our React components like never before.

Your First Styled Component

Let's create our very first styled component. We'll start with something simple -- a button. In your project, create a new file called StyledButton.js and add the following code:


import styled from 'styled-components';

const StyledButton = styled.button`
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
`;

export default StyledButton;

Enter fullscreen mode Exit fullscreen mode

What's happening here? We're importing the styled function from 'styled-components' and using it to create a styled button element. The CSS is written within a template literal (those backticks), allowing us to write multi-line CSS easily.

Now, let's use this button in our App.js:


import React from 'react';

import StyledButton from './StyledButton';

function App() {

  return (
    <div className="App">
      <h1>Welcome to React Styled Components</h1>
      <StyledButton>Click me!</StyledButton>
    </div>

  );

}

export default App;

Enter fullscreen mode Exit fullscreen mode

Run your app, and voila! You should see a nice green button that says "Click me!". Congratulations, you've just created and used your first styled component!

Diving Deeper: Props and Dynamic Styling

Using Props in Styled Components

One of the coolest features of Styled Components is how easily we can use props to dynamically style our components. Let's modify our StyledButton to accept a primary prop that changes its color:


import styled from 'styled-components';

const StyledButton = styled.button`

  background-color: ${props => props.primary ? '#4CAF50' : '#008CBA'};
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;

`;

export default StyledButton;

Enter fullscreen mode Exit fullscreen mode

Now we can use it like this in our App.js:


import React from 'react';
import StyledButton from './StyledButton';

function App() {

  return (
    <div className="App">
      <h1>Welcome to React Styled Components</h1>
      <StyledButton primary>Primary Button</StyledButton>
      <StyledButton>Secondary Button</StyledButton>
    </div>

  );

}

export default App;

Enter fullscreen mode Exit fullscreen mode

Cool, right? We now have two buttons with different colors, all controlled by a simple prop!

Extending Styles

Sometimes, you might want to create a new component based on an existing one, but with some modifications. Styled Components makes this super easy with the styled() function:


import styled from 'styled-components';
import StyledButton from './StyledButton';

const LargeButton = styled(StyledButton)`
  font-size: 24px;
  padding: 20px 40px;
`;

export default LargeButton;

Enter fullscreen mode Exit fullscreen mode

Now we have a LargeButton component that inherits all the styles from StyledButton but with a larger font size and padding.

Advanced Techniques: Global Styles and Theming

Adding Global Styles

While Styled Components are great for component-specific styles, sometimes we need to add global styles to our app. We can do this using the createGlobalStyle function:


import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`

  body {
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
  }

`;

export default GlobalStyle;

Enter fullscreen mode Exit fullscreen mode

To use this, we can add it to our App.js:


import React from 'react';
import StyledButton from './StyledButton';
import GlobalStyle from './GlobalStyle';

function App() {

  return (
    <>
      <GlobalStyle />

      <div className="App">
        <h1>Welcome to React Styled Components</h1>
        <StyledButton primary>Primary Button</StyledButton>
        <StyledButton>Secondary Button</StyledButton>
      </div>
    </>

  );

}

export default App;

Enter fullscreen mode Exit fullscreen mode

Implementing Theming

Theming is a powerful feature in Styled Components that allows us to define a set of shared variables that can be used across our styled components. Let's create a simple theme:


// theme.js

export const lightTheme = {
  body: '#FFF',
  text: '#363537',
  toggleBorder: '#FFF',
  background: '#363537',
}

export const darkTheme = {
  body: '#363537',
  text: '#FAFAFA',
  toggleBorder: '#6B8096',
  background: '#999',
}

Enter fullscreen mode Exit fullscreen mode

To use this theme, we need to wrap our app in a ThemeProvider:


import React from 'react';
import { ThemeProvider } from 'styled-components';
import { lightTheme, darkTheme } from './theme';
import GlobalStyle from './GlobalStyle';
import StyledButton from './StyledButton';

function App() {
  return (
    <ThemeProvider theme={lightTheme}>
      <>
        <GlobalStyle />

        <div className="App">
          <h1>Welcome to React Styled Components</h1>
          <StyledButton primary>Primary Button</StyledButton>
          <StyledButton>Secondary Button</StyledButton>
        </div>

      </>

    </ThemeProvider>

  );

}

export default App;

Enter fullscreen mode Exit fullscreen mode

Now we can access our theme in any styled component:


import styled from 'styled-components';
const StyledButton = styled.button`

  background-color: ${props => props.primary ? props.theme.background : '#008CBA'};
  color: ${props => props.theme.text};
  // ... other styles

`;

export default StyledButton;

Enter fullscreen mode Exit fullscreen mode

Best Practices and Tips

Organizing Your Styled Components

As your project grows, you might find yourself with a lot of styled components. Here are some tips to keep things organized:

1. Keep related styled components in the same file as your React component.

2. For larger components, consider creating a separate styles.js file in the same directory.

3. Use meaningful names for your styled components to make your code more readable.

Performance Considerations

Styled Components are generally very performant, but here are a few tips to ensure your app stays speedy:

1. Use the styled function for static styles and props for dynamic styles.

2. Avoid creating new styled components inside your render method.

3. Use the attrs method for frequently changing props to reduce the number of new class generations.

Testing Styled Components

Testing styled components is similar to testing regular React components. You can use tools like Jest and React Testing Library. Here's a simple example:


import React from 'react';
import { render } from '@testing-library/react';
import StyledButton from './StyledButton';

test('StyledButton renders correctly', () => {
  const { getByText } = render(<StyledButton>Click me</StyledButton>);
  expect(getByText('Click me')).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

Conclusion: Styling with Confidence

And there you have it, folks! We've journeyed through the world of React Styled Components, from creating our first styled component to implementing advanced features like theming. By now, you should feel confident in using Styled Components to create beautiful, maintainable, and dynamic user interfaces in your React applications.

Remember, the key to mastering Styled Components is practice. So go ahead, start styling your React apps with this powerful tool. Experiment with different styles, play with props, and see how Styled Components can transform your development workflow.

Happy styling, and may your React components always look fabulous!

Now, armed with React Styled Components, you can let your components speak volumes about your design skills. Keep coding, keep learning, and most importantly, have fun styling!

Top comments (0)