image
author

William Dawson

Full Stack Developer

Styled components are a CSS-in-JS tool that strikes a balance between components and styling, providing various applications to functionally and reusably get you up to speed in styling components. In this blog, we are going to be explaining the installation and setting up process of Styled Components.

Installation

Styled components can be installed simply by npm:

npm install styled-components

Setting up

Let’s have a look at the documentation example for this library making use of buttons. Now, button can be used for various functions and can be used with unique styles in different regions of the app (which is what we are basically doing right now). Styled components will allow you to hold all of the CSS in one place. To start-off, import styled-components into the component file:

import styled from 'styled-components';

Now to use it, use double back ticks `, like so:

const Button = styled.button``;

Now, when adding styles to components, you need to call this:

styled.nameOfElement``;

Note that the nameOfElement here must be a HTML element like buttonspan , div etc.
Now, to add styling to the button component created above,

const Button = styled.button`
background: black;
color: white;
border-radius: 7px;
padding: 20px;
margin: 10px;
font-size: 16px;
:disabled {
opacity: 0.4;
}
:hover {
box-shadow: 0 0 10px yellow;
}
`;

Note that from what we mentioned above, you can simply use normal CSS properties along with pseudo selectors like :disabled , :hover etc. in the same jsx file as the component defined.
Now, this button can be used as a part of normal JSX like:

<div>
<Button>
press me
</Button>
</div>

This Button component may now be merged with all the HTML or JSX elements just like the HTML element button, because it is one, along with some added CSS styling.
Using props to manipulate styling
The styled-component the library can put up styles conditionally through some particular props. Thus, current attributes can be used along with the custom ones.
Below, there’s an example of defining a primary button.
Of course, the primary button can be styled differently than the secondary or other sorts of button

<Button primary>Click this primary button!</Button>

Now, the current Button the component needs to be updated to accept primary as a prop and style differently when it receives this prop like:

${props => props.primary && css`
`}

Therefore, make use of the ${} to signal that some conditional logic has to run and refer to something called props. As it can be noted from above, props.primary has to be truthy. If that is the situation then some particular CSS styling can be impleented like this:

const Button = styled.button`
background: black;
color: white;
border-radius: 7px;
padding: 20px;
margin: 10px;
font-size: 16px;
:disabled {
opacity: 0.4;
}
:hover {
box-shadow: 0 0 10px yellow;
}
${props => props.primary && css`
background: green;
color: white;
`}
`;

Did you note the css attribute as well in the above condition? This css attribute needs to be imported from library as well. Thus, update the import statement as:

import styled, { css } from 'styled-components';

Another interesting example of how the styling can be manipulated conditionally based on props:

const Button = styled.button`
background: black;
color: white;
border-radius: 7px;
padding: 20px;
margin: 10px;
font-size: 16px;
:disabled {
opacity: 0.4;
}
:hover {
box-shadow: 0 0 10px yellow;
}
${props => props.primary && css`
background: green;
color: white;
`}
border-radius: ${props => (props.round ? '50%' : '7px')}
`;

To trigger this round bordered button or circular button, pass round as a prop like:

<Button round>Click this round button!</Button>

Styling an existing component
Let us assume that there is an existing component in the app which isn’t using styled-components as of now.

// TextArea.jsimport React from 'react';
import PropTypes from 'prop-types';const TextArea = ({ text }) => (
<div> TextArea: {text}</div>
);
TextArea.propTypes = {
text: PropTypes.string,
};
export default TextArea;

Now to style this one, the styled function should be used in a little different way.
The styled needs to be called like a function with the component as a parameter like so:

const StyledTextArea = styled(TextArea)`
// define styles
`;
<StyledTextArea text={"nice style!"} />

In the component pass className as a parameter in the props and assign that to a top-level div, like so:

// TextArea.js
import React from 'react';
import PropTypes from 'prop-types';const TextArea = ({ text, className }) => (
<div className={className}> TextArea: {text}</div>
);
TextArea.propTypes = {
text: PropTypes.string,
className: PropTypes.any,
};
export default TextArea;

Thus, calling the styled() function means that it under the hood creates a className that it injects into the component that required to be set to the top-level element, for it to take effect.

To Sum Up

Styled components are “visual primitives for components” in React’s own terms, and their purpose is to give everyone a versatile way to style components. A close coupling between parts and their styles is the result.

Note: Styled components are present for both React and React Native, and while you should certainly check out the React Native guide, our emphasis here will be on styled React components.

Want to read more such helpful blogs? Head to Codersera to get your hands on various detailed articles on technologies, programming languages, installation guides, and much more.

What are Styled Components?

styled-components utilize tagged template literals to style your components. It eliminates the mapping between components and styles. This implies that when you determine your styles, you actually create a normal React component that has your styles attached to it.

Should I use styled-components?

Styled Components certainly put styling and element architecture issues apart and allow components to be more readable. In addition, when you have components that depend on JavaScript for their style, Styled Components returns control of these states to CSS instead of using a multitude of conditional class names.

Are styled-components only for React?

Styled components are available for both React and React Native.

How useful was this post?

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Please do Rate Us and Share!

Related Blogs

  • author
    Adam Davidson

    Beginner’s Guide To SQL

    This beginner’s guide to SQL will have you learn the basics of SQL, short for structured programming language. SQL is a standard programming language primarily designed to store, retrieve, manage or modify data within a relational database management system (RDBMS).  It is the most commonly used database language endorsed by prominent relational database systems, such as MySQL,...

  • author
    Thomas Wilfred

    Python Vs Javascript: A Detailed Comparison

    Python vs JavaScript. How often do you come across these terms? Unless you are living under a rock, you must have heard of each of these and must also have wondered what these are. And if you are a developer, you must already have also used either of these languages. When talking about Python...

  • author
    Adam Davidson

    Top 12 Python Libraries For 2021

    When talking about the data science world, Python is increasingly becoming a go-to language and is one of the key aspects hiring managers are searching for in the skill set of a data scientist. It has been repeatedly ranking at the topmost position at the global data science surveys and its universal success just keeps growing!...

image

About The Author

William is a CTO and a full-stack engineer with 10 years of experience. He has spent the past seven years doing web and mobile apps. He’s good at designing architecture and implementing agile development process. The technologies he’s worked with include: Node.js, Elixir, Rails, AngularJS, React, React Native, Objective-C, iOS, Java, Android. He’s also familiar with C++, Haskell, C#/.NET. He is an enthusiastic programmer and a great guy to know

Try our One-Week Risk Free Trial for Hiring a Coder

Know more Hire a Coder

Hire Top 1% Remote Developers, Free For The First Week

Connect with quality remote developers and code your ideas away.

X