© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
D. B. Duldulao, R. J. L. CabagnotPractical Enterprise Reacthttps://doi.org/10.1007/978-1-4842-6975-6_17

17. Styling Methods for React Components

Devlin Basilan Duldulao1   and Ruby Jane Leyva Cabagnot1
(1)
Oslo, Norway
 

In the previous chapter, we made our app mobile-friendly with the help of media query Hooks. Now our app is almost ready to be deployed. However, before we proceed to do that, I think we should briefly pay attention to other styling methods for React components.

Throughout the application, we used the Material-UI library as our styling preference. But there are several other popular methods out there. We will not be diving deeply into each styling method but rather inform you of your other options.

There are various ways we can style React components. For many of us, choosing one over the other depends on different factors such as the architectural or design goals of our current project, a particular use case, and, of course, personal preferences.

For example, in some cases, when you just need to add a few style properties in a particular file, then maybe inline styling is the best option. And in the case of when you find yourself reusing some style properties in the same file, then styled-components are perfect. For other complex applications, you could look into CSS Modules or even the regular CSS.

Inline Styling

Developers typically use inline styling to prototype a component or test the component’s CSS styling. This styling is also a way to brute-force an element to see the outcome of any CSS inline style we write and remove. Inline styling is perhaps the most straightforward styling method we can use, albeit not recommended for large-scale applications.

One thing to remember is that in React, inline styling is specified as an object, not as a string. The key value is the CSS property name and should be written in camelCase, and the style’s value is usually a string.

So let’s try that.

In the components folder, let’s create a new file and name it InlineStyle.tsx.
import React from "react";
const heading = {
  color: "orange",
  fontSize: "50px",
};
function InlineStyle() {
  return (
    <div>
      {/* style attribute to equal to the object it is calling */}
      <h1 style={heading}> Inline Style</h1>
    </div>
  );
}
export default InlineStyle;
Listing 17-1

InlineStyle.tsx

Plain CSS

This is just your standard plain CSS . Easy and straightforward to use. No dependencies and has native browser support. However, this is not typically used in React projects, especially large-scale ones.

Let’s do a button example using this styling method. We are creating a button class with the following properties. We’re also adding a background color for the hover class.

Create a file and name it Plain.css, as shown in Listing 17-2.
.button {
    align-items: center;
    display: inline-flex;
    justify-content: center;
    padding: 6px 16px;
    border-radius: 3px;
    font-weight: 50;
    background: rgb(43, 128, 77);
    color: rgb(241, 240, 240);
    border: 1px solid rgb(249, 200, 200);
    box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 2px;
    width: auto;
    margin-top: 500px;
    margin-bottom: 1px;
    cursor: pointer;;
}
.button:hover {
    background-color: #d4bd54;
}
Listing 17-2

Plain CSS Styling

I added a few styling properties for aesthetic purposes, but the main focus is creating the CSS file. We have the named elements that are using classes. This allows us to reuse the elements in our components.

And then let’s use this button styling. We just imported the CSS file and then used the button class. And since this is React, we need to use className because the word class is a reserved keyword in JavaScript.
import React from "react";
import "./Plain.css";
const Button = () => {
  return (
     <>
      <Container>
        <button className="button"> Log in </button>
      </Container>
    </>
  );
};
Listing 17-3

Plain CSS Styling in your React component

Global CSS

Essentially, they are written the same as plain CSS. The main difference is that global CSS is ideal for using shared layout components such as Header components, navigation bar, dashboard, and other shared sites.

We can also create global CSS in our root index directory, as in the following case. We made an index.css and imported it into our root index file.
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',  'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans',
  'Helvetica Neue', sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;
}
Listing 17-4

Global CSS in index.css

And then import it in the index.tsx to be used globally.
.GlobalButton-root {
    background-color: #792b78;
    box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
    padding: 7px 14px;
}
.GlobalButton-root:hover {
    background-color: #d49254;
}
.GlobalButton-label {
    color: #fff;
}
Listing 17-5

Global CSS in index.tsx

In this case, we are applying the styling of index.css on all our app components.

CSS Modules

All the class names by default are locally scoped or apply only to a particular component. This means that each React component has its own CSS file, which is scoped locally to that file and component, thus preventing name collisions or specificity issues.

For dependencies, css-loader is used. Create-react-app supports CSS Modules out of the box.
.button {
  background-color: #406040;
  box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
  padding: 7px 14px;
}
.button:hover {
  background-color: #a08884b;
}
Listing 17-6

Button.module.css

Let’s create another stylesheet using button and name it another-stylesheet.css, as shown in Listing 17-7.
.button {
    color: #f4f466;
}
Listing 17-7

another-stylesheet.css

We can use the same CSS class name in different files in our app without worrying about name clashes. Let’s see how it works as shown in Listing 17-8 in ButtonModule.tsx.
import React from 'react';
// import css modules stylesheets as styles
import styles from './Button.module.css';
import "./another-stylesheet.css";
export default function ButtonModule() {
  return (
    <div>
      <button className={`${styles.button} button`}> Button Module</button>
    </div>
  );
}
Listing 17-8

ButtonModule.tsx

We used template literal or the backtick plus dollar sign to put the style object from the modules.css. The plain or regular CSS is used as a string.

See Figure 17-1.
../images/506956_1_En_17_Chapter/506956_1_En_17_Fig1_HTML.jpg
Figure 17-1

Screenshot of the Button Module UI

CSS-in-JS

Styled-components allow us to style React components and restyle existing components. We use props if we want to make changes in object styling.

Emotion in React, on the other hand, supports both string and object styles. The syntax is also more like CSS.

Styled-Components Library

Styled-components allow us to write regular CSS and pass functions and props in our application. We can use styled-components to any component as long as it accepts a className prop.

Styled-components use tagged template literals – the CSS code is written between two backticks – to style the components.
import styled from "styled-components";
//you can rename your classes however you want.
export const ButtonStyled = styled("button")`
  align-items: center;
  display: inline-flex;
  justify-content: center;
  padding: 6px 16px;
  border-radius: 3px;
  font-weight: 50;
  background: rgb(49, 85, 77);
  color: rgb(241, 240, 240);
  border: 1px solid rgb(249, 200, 200);
  box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 2px;
  width: auto;
  margin-top: 500px;
  margin-bottom: 1px;
  cursor: pointer;
  &:hover {
    background-color: #95503a;
  }
`;
export const Container = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  height: 1px;
  color: #5a3667;
`;
Listing 17-9

ButtonStyled Style Class

Next, use the Button style class. The mapping between components and styles is removed; this means you just create a standard React component and attach your styles to it – you only directly used <ButtonStyled> instead of using a <div> with a className.

We can also use props to style our styled-components, like how props are passed to regular React components.
import React from "react";
import { ButtonStyled, Container } from "./styles";
const Button = () => {
  return (
     <>
      <Container>
        <ButtonStyled>Log in</ButtonStyled>
      </Container>
     </>
  );
};
export default Button;
Listing 17-10

Button.tsx Using ButtonStyled Styling Class

Emotion in React

I have to emphasize “Emotion in React” here because there are two methods of using Emotion – one is framework agnostic and the other is with React.

This means the installation is also different. For more info on this, you can check out the official documentation here:

https://emotion.sh/docs/introduction

We will, of course, focus on the React method.

But within the React method, there are also two main approaches of styling elements – with CSS prop or using styled-components. We will just cite an example of the latter.

Using styled-components in Emotion, the package is @emotion/styled.

For the CSS prop, read more on the documentation here: https://emotion.sh/docs/css-prop.
import styled from "@emotion/styled";
export const ButtonEmotion = styled("button")`
  align-items: center;
  display: inline-flex;
  justify-content: center;
  padding: 6px 16px;
  border-radius: 3px;
  font-weight: 50;
  background: rgb(85, 49, 74);
  color: rgb(241, 240, 240);
  border: 1px solid rgb(249, 200, 200);
  box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 2px;
  width: auto;
  margin-top: 500px;
  margin-bottom: 1px;
  cursor: pointer;
  &:hover {
    background-color: #134f0e;
  }
`;
export const Container = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  height: 1px;
  color: #5a3667;
`;
Listing 17-11

Emotion Styling Component

The styled-component uses the styled.div style API for creating components.

Summary

As we have stated at the beginning of this chapter, there are different ways or methods to style React components. There are a lot of factors for choosing one over the other. We have outlined just a few of them here, from the most basic such as inline styling to CSS Modules and popular styling libraries including styled-components and Emotion.

The next chapter is essentially the culmination of our project app as we deploy it using two different ways: Netlify and Docker.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.81.57.77