Installing and setting up styled-components

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, buttons 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 backticks `, like so:

const Button = styled.button``;

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

styled.nameOfElement``;

Note that the nameOfElement there must be an HTML element like button, span , 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 js 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 the 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 above, props. primary has to be truthy. If that is the situation then some particular CSS styling can be implemented 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 the 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.jsimport 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 is 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. 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.

FAQ's

What are Visual Primitives?

Visual primitives can be considered as abstractions of those informative subsets of an image that are of interest in a given vision task. After discussing their nature and some problems related to their extraction, pattern description in terms of primitives is considered.

How do we style components in React Native?

With React Native, you style your application using JavaScript. All of the core components accept a prop named style. The style names and values usually match how CSS works on the web, except names are written using camel casing, e.g. backgroundColor rather than the background color.

Why do React and React Native have styled-components?

Styled-components is a CSS-in-JavaScript library that allows you to use component-level styles in your application. It is easy to maintain and saves you the stress of remembering, duplicating, or misspelling class names. React Native is an open-source mobile application framework.