Simplify Styling React with Styled Components

Simplify Styling React with Styled Components

React has always been my first choice for developing front-end for websites. It comprises functional components that make everything easy. But styling React Components has always been complicated as there was no direct way for styling. In this article, I'd like to introduce Styled Components.

Styled Components: Style on the go in React

Styled components are the modern way of styling in React. It uses the default HTML tags and allows you to make customized components using them.

  • Installation

To install styled-components, run:

npm install --save styled-components
  • Import

To start using styled-components, you import like this:

import styled from 'styled-components';
  • Get Started

Now that you have imported styled-components into your file, you can start styling your components. If you want a Login Button Component, you can call a Button Component using the styled object like this:

const LoginButton = styled.button``

Remember: You can assign any name to your const holding the styled-components.

That gives you a simple button.

Next, to customize your component, you can effortlessly start adding CSS inside the back-ticks:

const LoginButton = styled.button`
  text-align: center;
  border-radius: 5px;
  border: 1px solid #7FAAD4;
  background-color: #7FFFD4;
  color: white;
  padding: 10px 22px;
  text-decoration: none;
  display: inline-block;
  font-size: 18px;
  margin: 4px 2px;
  cursor: pointer;
`;

Feel free to style it however you like.

You can now use this Login Button Component inside your code.

  • Example Code

import React from 'react';
import styled from 'styled-components';

const LoginButton = styled.button`
  text-align: center;
  border-radius: 5px;
  border: 1px solid #7FAAD4;
  background-color: #7FFFD4;
  color: white;
  padding: 10px 22px;
  text-decoration: none;
  display: inline-block;
  font-size: 18px;
  margin: 4px 2px;
  cursor: pointer;
`;

const App = () => {
  return (
    <div>
      <LoginButton>Login</LoginButton>
    </div>
  );
};

export default App;
  • Benefits

  1. We do not need a separate CSS file for styling or in-line styling.
  2. This package does not limit the CSS. We can use media queries, nesting, conditional rendering, and anything else we might need.
  3. It is also easier to conditionally render a component. Say No to confusing classNames.

Endless Customization for your Component

Styled Components are similar to the React Native Stylesheet. You can be a lot more creative while designing your websites as styled-components simplify styling in React. You can read their official documentation here.

Here's a popular website that used Styled Components: zillow.com

Thanks a lot for reading this article! If you find this helpful, do give it a like and share. Feel free to share your feedback and ask questions down in the comment section. Cheers!