Create react app project with modern CSS

Time:2020-5-22

Create react app project with modern CSS

  • Source code( ChainDesk.CN )Content editing
  • Wish code slogan | connects each programmer’s story
  • Website| http://chaindesk.cn
  • Willing code vision | to create a free course of IT system for the whole discipline, help Xiaobai users and junior engineers to learn free system at zero cost and advance at low cost, help bat senior engineers grow and use their own advantages to create post sleep income.
  • Official account number, code of wishes, service code, block chain, tribe
  • Free join the code of thinking community of engineers, any official account reply “wish code” two characters to get into the group two-dimensional code.

Reading time: 13min

Before using the create react app, you didn’t actually have many options to clean up visually. Often at randomCascading style sheetsCSS)Project maintainers come up with a new idea and try to make other libraries, frameworks or preprocessors involved in project compilation a nightmare.

The preprocessor in the context of create react app is basically a step in the build process. In this case, we’re talking about something that takes some style code (CSS or other format), compiles it into basic CSS, and adds it to the output of the build process.

In this article, we’ll cover a variety of materials covering style related features and highlight one of the best new features in the create react app in my opinion: support for CSS modules and sass.

Introduce CSS module


CSS modules can modularize any CSS code you import in a way that prevents the introduction of global overlapping namespaces, although the end result is still a huge CSS file.

Better project organization

Let’s clean up the directory structure in our project first. All we have to do is separate each component with CSS and JavaScript code into its own folder. First, create the new todo, todo, app, todolist, and provider folders, and put all their related code in each of them.

We also need to create a new file in each called directory, which index.js Only import and export the corresponding components. For example, an app index file (SRC / APP/ index.js )It will be as follows:

import App from "./App";
export default App;

Todo (src/Todo/ index.js )The new index file for is as follows:

import Todo from "./Todo";
export default Todo;

Based on this pattern, you can guess the contents of index files, such as newtodo, todolist and their dividers.

Next, we need to change each location that references these files to make it easier to import all of them. Unfortunately, it’s going to be tedious work, but we need to do the same thing to make sure we don’t break anything in the process.

First, src/App in/ App.js , change the todolist import component to the following:

import TodoList from "../TodoList";

We don’t need to do anything, divider because it’s a component that hasn’t been imported. New todo and todo are similar types, so we can skip them as well. src/TodoList/ TodoList.js On the other hand, we need to deal with many things, because it is one of our highest level components and imports a lot:

import Todo from "../Todo";
import NewTodo from "../NewTodo";
import Divider from "../Divider";

But that’s not all. Our test file Src / todolist/ TodoList.test.js We also need to modify these new paths to include files, otherwise our test will fail! We need almost the same import list as before:

import TodoList from "./TodoList";
import NewTodo from "../NewTodo";
import Todo from "../Todo";

When you reload your application, your code should still work, the tests should all pass, and everything should be clean! Our complete project structure should now look like this:

src/
  App/
    App.css
    App.js
    App.test.js
    index.js
  Divider/
    Divider.css
    Divider.js
    index.js
  NewTodo/
    NewTodo.css
    NewTodo.js
    NewTodo.test.js
    index.js
  Todo/
    Todo.css
    Todo.js
    Todo.test.js
    index.js
  TodoList/
    TodoList.css
    TodoList.js
    TodoList.test.js
    index.js
  index.css
  index.js
  setupTests.js
  ... etc ...
Bringing CSS modules into our applications

If we want to use CSS modules, we need to follow some simple guidelines. First, we need to name our file [whatever] module.css , instead of [whatever]. CSS. The next thing we need to do is make sure our style is simple to name and easy to reference. Let’s first follow these conventions and rename our CSS file to todoas Src / todo/ Todo.module.css , and then we’ll change a little bit:

.todo {
  border: 2px solid black;
  text-align: center;
  background: #f5f5f5;
  color: #333;
  margin: 20px;
  padding: 20px;
}
.done {
background: #f5a5a5;
}

Next, we will open Src / todo/ Todo.js To take advantage of CSS modules. We created a helper function in our todo component, cssclass (), which returns the style we should use in the component, and we don’t need to make changes to make everything exactly the same as before. We also need import to change our statement at the top because we renamed the file and are changing the way our CSS is loaded into the code! Look at the following:

import styles from "./Todo.module.css";

This allows our code to Todo.module.css Use any of the defined class names styles. [classname] by referencing them. For example, in the previous file, we defined two CSS class names: todo and done, so we can now use the styles.Todo And reference them in components styles.done 。 We need to change the cssclass() function to use it, so let’s make those exact changes now. In Src / todo/ Todo.js , our cssclass() function should now look like this:

  cssClasses() {
    let classes = [styles.todo];
    if (this.state.done) {
      classes = [...classes, styles.done];
    }
    return classes.join(' ');
  }

Save and reload, our application should return to normal! Next, let’s change the label todo inside component HR to have its own style and effect. Return to Src / todo/ Todo.module.css Add the following blocks to our HR tag, and we will give a new class reddivider:

.redDivider {
  border: 2px solid red;
}

Finally, return our render() function Src / todo/ Todo.js , and save and reload the HR tag of the render() function with changes. Now we should fully partition the CSS code without worrying about conflicts and global namespaces! This is what the output looks like:

Create react app project with modern CSS

Composability with CSS module

This is not all the CSS module gives us, although it is certainly an important part of the CSS module, we get it immediately and effortlessly. We also get CSS composability, which can inherit CSS classes from other classes, whether they are in the main file or not. This can be useful when you set up more complex nested components that all need to work with slightly different stylesheets, but not much different from each other.

Suppose we want to be able to mark some components as critical rather than just regular todos. We don’t want to make too many changes to the component; we want it to inherit the same basic rules as all other todos. We need to set up some code to achieve this. Back to Src / todo/ Todo.js , we will make some changes to allow a new state attribute named critical. We will start with the constructor component, and we will add the new state property and bind function tag:

 constructor(props) {
    super(props);
    this.state = {
      done: false,
      critical: false
    };
this.markAsDone = this.markAsDone.bind(this);
this.removeTodo = this.removeTodo.bind(this);
this.markCritical = this.markCritical.bind(this);
}

We add a new attribute to the critical attribute, state, and set it to the default value of false. Then we also referenced a function (we haven’t written yet) markcritical, and we bound this because we’ll use it later in the event handler. Next, we will solve the problem markcritical():

  markCritical() {
    this.setState({ critical: true });
  }

We also need to modify our CSS classes () function so that it can react to this new state property. To demonstrate the composability of CSS modules, we set the classes as an empty array, and then the first item becomes critical or todo, depending on whether the item is marked critical or not

 cssClasses() {
    let classes = [];
    if (this.state.critical) {
      classes = [styles.critical];
    } else {
      classes = [styles.todo];
    }
    if (this.state.done) {
      classes = [...classes, styles.done];
    }
    return classes.join(' ');
  }

Finally, in our render function, we will create a button tag to mark the item critical:

  render() {
    return (
      

        {this.props.description}
        

          Mark as Done
        
        
          Remove Me
        
        
          Mark as Critical
        
      

    );
  }

We haven’t finished yet, although we have at least 90% of the way. We also want to go back to Src / todo/ Todo.module.css And add a new block for the critical class name. We will also use our composable attributes:

.critical {
  composes: todo;
  border: 4px dashed red;
}

To use composition, all you need to do is add a new CSS property, compose and specify a class name (or multiple class names) for it. In this case, writing is a strange way of saying that it inherits the behavior of other class names and allows you to override other class names. In the previous example, we said critical is a CSS module class, which is based on a todo model and added a large red dotted component of border, because we just said that it means it is critical.

Save and reload as usual, you should be able to mark items as complete, critical or both, or delete them by clicking delete me, as shown in the following screenshot:

Create react app project with modern CSS

This is our brief introduction to CSS module! Before proceeding, you also need to quickly update the test snapshot yarn test by clicking u on the screen.

Introduce sass into our project


Sass is essentially CSS with extended function support. When I say extended feature support here, I mean it! Sass supports the following feature sets, which are missing from CSS:

·Variables

·Nesting

·Some CSS files

·Import Support

·Mix in

·Extension and inheritance

·Operators and calculations

Installing and configuring sass

The good news is that it’s easy to get sass support in the create react app project. We first need to install it through yarn or NPM.

$ yarn add node-sass

We will see a lot of its output, but assuming there are no errors and everything goes well, we should be able to restart our development server and start using some sass. Let’s create a more general utility sass file that will be responsible for storing the standardized colors we want to use throughout the application, as well as storing things in a neat gradient HR mode, in case we want to use it elsewhere.

We will also change some of the colors we are using to have some red, green and blue, depending on whether the project is critical, complete or neither. In addition, we need to slightly change our project and add a new file to get some idea of shared styles and colors. So let’s start:

  1. src/ shared.scss Create a new file in our project and provide it with the following principals:
$todo-critical: #f5a5a5;
$todo-normal: #a5a5f5;
$todo-complete: #a5f5a5;
$fancy-gradient: linear-gradient(
  to right,
  rgba(0, 0, 0, 0),
  rgba(0, 0, 0, 0.8),
  rgba(0, 0, 0, 0)
);
  1. Next, go to Src / divider/ Divider.css And rename the file Src / divider/ Divider.scss 。 Next, we will change the Divider.cssin References to Src / dividers for/ Divider.js , as follows:
import "./Divider.scss";
  1. Now we need to change the code Divider.scss To import and use variables as part of our shared variable file:
@import "../shared";
hr {
border: 0;
height: 1px;
background-image: $fancy-gradient;
}

So, we import Src / into the new shared sass file, and then the background image value only references the variable we created $family grade, which means that we can now recreate that fancy gradient when we need it without having to rewrite it repeatedly.

  1. Save and reload, and you should see no significant changes.

Mixed sass and CSS modules


The good news is that introducing sass into the CSS module in the create react app is basically not complicated. In fact, these steps are the same! So if we want to start mixing the two, all we need to do is rename some files and change our import processing. Let’s take a look at this action:

  1. First, return to our Src / todo/ Todo.module.css File and make a very small change. Specifically, let’s rename it Src / todo/ Todo.module.scss 。 Next, we need to change our import statement Src / todo/ Todo.js Otherwise the whole thing will collapse:
import styles from "./Todo.module.scss";
  1. Now, we should let our sass use the CSS module of todo component, so let’s start using it. Thirdly, we need to import our shared file to this file sass. Please note the following Src / todo/ Todo.module.scss :
@import '../shared';
  1. Next, we need to start changing references to various background colors. We changed the background of the regular todos to $todo normal. Then, we change the completed todo background to $todo complete. Finally, we will change the critical project to $todo critical:
.todo {
  border: 2px solid black;
  text-align: center;
  background: $todo-normal;
  color: #333;
  margin: 20px;
  padding: 20px;
}
.done {
background: $todo-complete;
}

.hr {
border: 2px solid red;
}

.critical {
composes: todo;
background: $todo-critical;
}
  1. Save and reload our project, let’s make sure the new color scheme is respected:

Create react app project with modern CSS

Now, we have a good integration of CSS module and sass in the create react app project without installing a single new dependency. We let them play well together, which is a greater achievement!