Skip to content

Lesson 3.1

Mary Alice Moore edited this page Jan 25, 2023 · 2 revisions

This lesson will teach you the following:

  • Cascading Style Sheets (CSS)
  • CSS Modules

Instructions

Overview

Because React is just JavaScript, you have more options for how to implement style with React than if you were developing an application using plain old HTML and CSS files.

Create React App has built into it the ability to load and bundle ordinary CSS files into your user interface.

import "styles.css";
 
function App{
 
   return (
      <div className="article-link">
         <h1 className="title">Today in React</h1>
         <p className="firstPara">Extra, extra read all about it…</p>
     </div>
   );
}
 
export default App; 

Importing a stylesheet into a React component has the benefit of being a familiar way to work, and it also allows you to use existing stylesheets that you may have.

As with importing styles into the HTML file, CSS imported into the components cascades to the component's children. The styles are imported into the parent component, but the class and element styles defined in the stylesheet are only used in the child.

React has built into it another way to style components that gives you all of the capabilities of a CSS preprocessor, without having to learn the language used by the CSS preprocessor: you can simply use JavaScript to apply style to components.

Inline Styling

React's built-in DOM elements have a style attribute that accepts a style object as its value. When you pass DOM style properties into this attribute, those properties will be applied to the resulting HTML element.

function Warning(props){
  return (
    <p style={{color:"red",padding:"6px"}}>
      {props.warningMessage}
    </p>
  )
}
 
export default Warning; 

The style object, written as an object literal must be surrounded by curly brackets to indicate that it's to be treated as literal JavaScript rather than JSX.

The properties that you can access and manipulate using JavaScript mirror the CSS properties, and you can do anything using JavaScript styles that you can do with CSS. But because of the differences between JavaScript and CSS, JavaScript styles are written differently.

The first difference is that a CSS rule-set does not follow the rules of JavaScript object literals, although it does resemble one.

  • The individual rules in CSS are separated by semicolons, while in JavaScript objects, properties are separated by commas.
  • CSS property names can normally contain more than one word have hyphens between the words. In JavaScript, this would result in an error, so JavaScript style properties use camelCase for multi-word names.

When to use inline styles

If you're only applying a couple of style properties to an element, and you're not going to reuse that particular combination of properties in another component, writing them as inline styles is easy and fast. Using inline styles also increases the portability of a component, since the styles are part of the component file and don't rely on an external module being present.

When not to use inline styles

In a React application with many different components, using inline styles can become a maintenance nightmare. It's simply a good user interface design practice to reuse certain styles.

If you were to write the same style object, containing the same style properties, each time you styled a block of text, you'd soon come to the realization that writing inline style objects is a waste of effort. At that point, the thing to do is to create variables to store your style objects.

function Warning(props){

const warningStyle = {color:"red",padding:"6px"};

  return (
    <p style={warningStyle}>
      {props.warningMessage}
    </p>
  )
}
 
export default Warning; 

Variables created to hold style objects can be kept inside the component, or you can put them into separate files and export them using either named exports or a default export.

CSS Modules

CSS Modules give you some of the benefits of using JavaScript style objects while using standard CSS stylesheets. CSS Modules solves the problem of name conflicts and scoping in CSS.

CSS modules can be written like normal CSS files, and then imported into your components as if they were JavaScript. During the compilation of your components, CSS modules are converted into JavaScript Objects.

/* my-component.module.css */
.bigText {
  font-size: 4em;
}
 
.redText {
  color: #FF0000;
} 

To import the CSS module into a component, you need to name the file with .module.css at the end and use the following import statement:

import styles from './my-component.module.css';

When your component is compiled, the classes in the CSS module will be rewritten using a format called ICSS, which stands for Interoperable CSS.

import styles from './my-component.module.css';
 
function DisplayMessage(props) {
 
  return (<p className = {styles.redText}>This text is red.</p>);
 
}
 
export default DisplayMessage; 

CSS Modules isn't specific to React. It's a separate specification, which can be used with any front-end library. However, support for it is built into Create React App, so to use it in your React applications built using Create React App, you don't need to do anything special to start using it.

CSS module files can be just plain CSS, but they also have some additional capabilities that can make them more powerful than plain old CSS. By default, the rules you create in CSS module files are scoped locally to the component you import the styles into. If you want to create a global rule, you can do so by prefixing the name of the class with :global, like this:

:global .header1 {
  font-size: 2rem;
  font-weight: bold;
}

In this example, the header1 class will be available to all of your components.

CSS-IN-JS and Styled Components

CSS-in-JS refers to a pattern of composing styles using JavaScript. Several third-party libraries exist for implementing CSS-in-JS. Perhaps the most popular and commonly used is Styled Components.

Because Styled Components is a separate library, which is not installed by Create React App by default, the first step in using it is to install it:

npm install --save styled-components

Styled Components uses tagged template literals to let you write new components using CSS.

Styled Components creates a styled component that you can wrap around the elements you want to style. The result is that your JSX code is free from style objects, class names, and style attributes, because all the styling is done with reusable styled elements.

import styled from 'styled-components';

const Heading = styled.h1`
   width: 50%;
   margin: 0 auto;
   font-size: 2.2em;
   color: #333300;`

const ExampleComponent = ()=>{
   return(
        <Heading>Example Heading</Heading>
   );
}
export default ExampleComponent; 

Styled Components can be defined in separate files just like other components and then imported into multiple files, they can be nested to create more complex components through composition.

Now put this into action...

So far you've built a functional todo list, but now it's time to add some style!

There are multiple ways to work with CSS in React applications:

  • Inline CSS
  • CSS
  • CSS-in-JS

In this lesson, we would like for you to use CSS modules. Let's walk through an example:

  • Open src/
  • Create a CSS module file called TodoListItem.module.css
  • Add a ruleset for class ListItem that changes the text color
  • Open src/TodoListItem.js
  • Import the default module (as style) from TodoListItem.module.css
  • Add a className to the <li> element and set the value as the class from CSS module ({style.ListItem})
    • note: the style object represents all the class names in your CSS module file, so you access them like normal object properties (dot or bracket notation)

Rubric

For this assignment, there are some general requirements but the design is up to you. This is your chance to be creative and personalize your todo list application.

  • Change the background color of the page body
  • Change the default text color
  • Customize the font family
    • (Optional) Load in a font family from Google Fonts
  • Customize style of navigation items
  • Add spacing (padding/margin) between elements
  • Change the font size, weight, and color of all headings
  • Customize input and button styles
  • Use Media Queries to make sure the application is responsive for all device sizes (mobile, tablet, desktop, etc.)
  • (Optional) Add multi-media usage (i.e. iconography)

This is the basic rubric, but we encourage you to think beyond this list and come up with your own ideas to make your application unique!

Clone this wiki locally