React implements styles with five common strategies. I’m CUGGZ

React style strategies include the following:

  • Inline styles: Inline styles define inline styles directly within a JSX element.
  • CSS style Sheets: This is the most common style strategy we use, using separate style sheets, using CSS or SCSS to style elements;
  • CSS module: A CSS module is a file, and by default all class and animation names are locally scoped;
  • Styled Components: This is a styled component library for React and React Native, which allows us to use component-level styles in early applications. These styles are written using CSS-in-JS technology;
  • JSS: JSS is a CSS authoring tool that allows us to use JavaScript to describe styles in a declarative, conflict-free, and repeatable way.

While this may sound a bit abstract, let’s take a look at how each of these style strategies is used, as well as their strengths and weaknesses.

1. Inline style

React components are made up of JSX elements, which are not written in regular HTML, but can still be styled using inline styles. The only difference from normal HTML inline style is that the inline style in JSX is an object, not a string.

Here’s a simple example:

import React from "react";

export default function App() {
  return (
      <h1 style={{ color: "red" }}>Hello World</h1>
  );
}
Copy the code

This component is very simple. In the style property above, the curly braces are used to tell the JSX parser that the content in the curly braces is JavaScript, not a string. The curly braces inside are used to initialize an object.

When more than one word appears in a style attribute, use a camel name. For example, the text-align attribute must be textAlign:

import React from "react";

export default function App() {
  return (
      <h1 style={{ textAlign: "center" }}>Hello World</h1>
  );
}
Copy the code

Since the style property is an object, we can also define this object as a constant to separate styles, so that we can reuse it on other components as needed:

import React from "react";

const h1Style = {
  color: 'red',
  textAlign: "center"
}

export default function App() {
  return (
      <h1 style={h1Style}>Hello World</h1>
  );
}
Copy the code

If you want to continue extending the style object when it is reused, you can do so using the extension operator in ES6:

import React from "react"; const h1Style = { color: 'red', textAlign: "center" } export default function App() { return ( <h1 style={{... h1Style, fontSize: '25px'}}>Hello World</h1> ); }Copy the code

In addition, we can also use variables in the style object, so that the style can change dynamically:

import React from "react";

export default function App({themeColor}) {
  const h1Style = {
    color: themeColor,
    textAlign: "center"
  }

  return (
      <h1 style={h1Style}>Hello World</h1>
  );
}
Copy the code

This is one of the most important features of inline styles. However, the React team doesn’t recommend using inline styles. Inline styles are also the most basic example of CSS-in-JS technology.

Advantages of inline style:

  • Simplicity of use: The advantage of using inline styles is that it is easy to add styles component-centric.
  • Convenient extension: through the use of objects for style Settings, you can easily extend the object to extend the style;
  • Collision avoidance: Styles are defined in the component as objects, avoiding collisions with other styles.

In large projects, inline styles may not be a good choice because they have limitations:

  • Pseudo classes cannot be used: this means :hover, :focus, : Actived, :visited, etc will not be used;

  • Media query cannot be used: Properties related to media query cannot be used.

  • Reduced code readability: If you use too many styles, the code readability will be greatly reduced.

  • No code hints: There are no code hints when defining styles using objects, so it’s hard to detect if the style attributes are misspelled.

2. CSS style sheets

CSS style sheets are probably the most common way to define styles. In addition to native CSS, the SASS preprocessor is now the most widely used to define styles. These stylesheets can be imported into the React component depending on where the styles are applied.

Here’s an example:

// style.scss
.box {
  margin: 40px;
  border: 1px solid black;
}

.box-content {
  font-size: 16px;
  text-align: center;
}
Copy the code

To use this style in the Box component, import the SASS file:

import React from 'react';
import './style.scss';

const Box = () => (
  <div className="box">
    <p className="box-content"> Hello World </p>
  </div>
);

export default Box;
Copy the code

In normal HTML, we use class to define a class, whereas in JSX we use className because class is a reserved word in JavaScript.

When using CSS style sheets as a style strategy, you can also use existing frameworks such as Bootstrap, which provide existing classes and components that can be inserted directly into React components without having to style each element.

Advantages of CSS stylesheets:

  • Separation of concerns: Separating styles from JavaScript and writing CSS syntax as usual;
  • Use all CSS features: This method allows us to use any SYNTAX of CSS, including pseudo-classes, media queries, and so on;
  • Caching and performance: Standard CSS files facilitate browser optimization, caching files locally thus allowing repeated methods to improve performance;
  • Easy to write: CSS stylesheets have code hints when written;

Of course, CSS stylesheets have their drawbacks:

  • Collision: CSS selectors all have the same global scope. If the selectors are used incorrectly, styles can clash.

  • Readability: If the structure is not correct, CSS or SASS stylesheets can become long and difficult to read as the application becomes more complex;

  • Difficult to clean up: As stylesheets become more complex, some old or unused style attributes become harder to clean up;

  • No true dynamic styling: It is difficult to set styles dynamically in CSS tables.

3. The CSS modules

All class and animation names in a CSS module default to local scoped CSS files. When using CSS modules, each React component has its own CSS style file, which can only be used in the corresponding component file. In this way, there are no class name conflicts at build time.

Here’s how the CSS module works with React:

//style.css
 :local(.container) {
   margin: 40px;
   border: 2px solid red;
 }
 :local(.content) {
   font-size: 15px;
   text-align: center;
 }
Copy the code

To use :local(.classname), you need to configure it in Webpack. We can add the corresponding loader to the Webpack:

test: /.css$/, loader: 'style! css-loader? modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'Copy the code

To use the CSS module in the Box component, you need to import the module file into the component for use:

import React from 'react';
import styles from './style.css';

const Box = () => (
  <div className={styles.container}>
    <p className={styles.content}> Styling React Components </p>
  </div>
);

export default Box;
Copy the code

Styles is a style object contained in style.css that contains all defined classes. This is the basic use of CSS modules.

Styles can also be inherited using CSS modules, using the composes keyword:

:local(.MediumParagraph) {
  font-size: 20px;
}

:local(.BlueParagraph) {
  composes: MediumParagraph;
  color: blue;
  text-align: left;
}

:local(.GreenParagraph) {
  composes: MediumParagraph;
  color: green;
  text-align: right;
}
Copy the code

In CSS modules, local styles (:local(…) are exported by default. ), you can also use (:global(…) ) to export global styles. Local styles are compiled to a uniquely identified class name, while global styles are compiled with the same name.

Advantages of using CSS modules:

  • Modularization: realize the modularization of style, avoid style conflict;
  • No duplication in SSR: No code duplication when using server rendering (SSR);

Disadvantages of using CSS modules:

  • Additional Build tools: Additional build tools are required (Webpack);

  • Writing trouble: Local and global modules are cumbersome to write;

  • Hump naming: Only hump naming is allowed.

4. styled-components

Styled Components is a style component library implemented using CSS-in-JS technology. It is a library designed for React and React Native. It allows us to use a mix of JavaScript and CSS to write stylesheet components in our applications. And it is sass-enabled, without the need to add any libraries.

Styled Components are used in more than half of all CSS-IN-JS schemes, according to HTTP Archive:

It operates in the same way as a CSS module, which is a way of writing CSS that is limited in scope to a single component and inaccessible to any other elements or even components on the page.

(1) Basic use

How do you use the Styled Components library? Let’s take a look at the following steps: (1) Install the library

npm install styled-components --save
Copy the code

(2) Introduction into the library

import styled from "styled-components";
Copy the code

(3) Define style components

import React from "react";
import styled from "styled-components";

const Title = styled.h1`
  font-size: 20px;
  text-align: center;
  color: red;
`;

export default function App() {
  return <Title>Hello World</Title>;
}
Copy the code

As you can see, its implementation is still very simple, and the syntax is: Styled. Tag name, followed by a template string whose content is the component’s style property. This creates a React component with styles.

(2) style nesting

We can also nest styles in style components, such as:

import React from "react";
import styled from "styled-components";

const Title = styled.div`
  text-align: center;

    img {
        height: 100px;
        width: 200px;
    }
    p {
        font-size: 20px;
    color: red;
    }
`;

export default function App({imgUrl}) {
  return (
    <Title>
        <p>Hello World</p>
        <img src={imgURl} alt="" />
    </Title>
  );
}
Copy the code

(3) Component parameter transfer

We can also pass parameters to the style component:

import React from "react";
import styled from "styled-components";

const Title = styled.div`
  text-align: center;

    img {
        height: 100px;
        width: 200px;
    }

    p {
        font-size: 20px;
    color: ${props => props.color};
    }
`;

export default function App({imgUrl, themeColor}) {
  return (
    <Title>
        <p color={themeColor}>Hello World</p>
        <img src={imgURl} alt="" />
    </Title>
  );
}
Copy the code

This allows you to dynamically change the color of the text.

(4) Class of the style component

The class name is defined by the style-components library. Here is an example:

const SeniorTitle = styled.h1`
    width: 100%;
    height: 29pt;
    line-height: 29pt;
    background-color: #E0F2E1;
    border-radius: 10pt;

    span {
        text-align: center;
    }

    p {
        font-size: 14pt;
        color: ${props => props.color};
    }
`;
Copy the code

The class name is CSS-1d3SPWA. The span style is compiled as follows:

.css-1d3spwa span {
    text-align: center;
}
Copy the code

(5) Style component inheritance

We can also use the styles of other components and inherit all of their styles (overwriting the inherited styles if they are the same), for example:

const BoringButton = styled.button` color: blue; Background - color: green. `; const CoolButton = styled(BoringButton)` color: pink; `;Copy the code

In this way, the following component takes the style of the above component and overwrites the duplicate style color.

(6) Use CSS helper functions

CSS helper functions come in handy if we need to use common styles in multiple style components. Let’s see how CSS helper functions are used:

import React from "react";
import styled, {css} from "styled-components";

const commonStyle = css`
  color: white;
    font-size: 20px;
`;

const Button = styled.button`
  ${commonStyle};
  background-color: red;
`;

const AnotherButton = styled.button`
  ${commonStyle};
  background-color: green;
`;
Copy the code

The commonStyle defined here does not have its own separate classes when used in the two Button components, but is added to the corresponding classes of the two Button components.

(7) Reference other style components

We can also reference other style components, similar to inheritance:

const BoringButton = styled.button` color: blue; Background - color: green. `; const CoolButton = styled.div` ${BoringButton} { color: pink; } `;Copy the code

(8) Use style components with TypeScript

If our project is written in React + TypeScript, we might get an error when passing props to the style component:We can generically define a props type for this component: props

interface ITitleWithoutNumber {
    paddingRight: string;
}


const TitleWithoutNumber = styled.h1<ITitleWithoutNumber>`

`
Copy the code

This limits the types of component props. If you want to add a new props value, you need to add a new parameter and type to the interface interface.

(9) Global theme

We can also use a global theme in style-components, which is implemented through the ThemeProvider API:

import React from "react";
import { ThemeProvider } from "styled-components";

const theme = {
  colors: {
    powderWhite: "#FFFDF9",
    persianGreen: "#06B49A",
    lightBlue: "#AFDBD2",
    onyx: "#36313D"
  },
  fonts: ["sans-serif", "Roboto"],
  fontSizes: {
    small: "1em",
    medium: "2em",
    large: "3em"
  }
};

const Theme = ({ children }) => (
  <ThemeProvider theme={theme}>{children}</ThemeProvider>
);

export default Theme;
Copy the code

Here we export a Theme component that provides a Theme Theme for sub-components to use as follows:

import React from "react";
import Theme from "./Theme";
import styled from "styled-components";

const Container = styled.div`
  width: 100%;
  border: ${props => `1px solid ${props.theme.colors.onyx}`};
  background-color: ${props => props.theme.colors.lightBlue};
  font-family: ${props => props.theme.fonts[0]};
`;

const Heading = styled.h1`
  font-size: ${({ isHeading, theme: { fontSizes } }) =>
    isHeading ? fontSizes.large : fontSizes.small};
  color: ${({ theme: { colors } }) => colors.persianGreen};
`;

const App = () => {
  return (
    <Theme>
      <Container>
        <Heading isHeading={true}>Hello World</Heading>
        <h2>styled-components</h2>
      </Container>
    </Theme>
  );
};
export default App;
Copy the code

You can use this approach to implement global themes.

(10) Advantages and disadvantages

Advantages of Style-Components:

  • Out-of-the-box Sass syntax: Support for out-of-the-box Sass syntax in style-Components without additional installation or setup;
  • Support for using themes: In styled- Components provides a ThemeContext, which can be passed directly as a theme object method, facilitating the use of global themes;
  • Dynamic Styles: You can use props to dynamically set and change styles;
  • No type conflicts: Style components generate unique class names that do not conflict with other component types;
  • Easy to maintain: we do not need to view the style in various style files, just need to view its style in the style component, easy to maintain;

Disadvantages of Style-Components:

  • Affect performance:Style-components are built to convert all style definitions in the React component to pure CSS and inject the content into the index.html file<style>Tag. In this way, the size of HTML files is increased and the output CSS cannot be partitioned, which affects the application performance.

5. JSS

JSS is a CSS authoring tool that allows us to use JavaScript to describe styles in a living, conflict-free, and reusable way. It can be compiled in Node.js at browser, server, or build time. JSS is a new style strategy that is framed-independent and consists of multiple packages: core, plug-in, framework integration, and so on.

In React, you can use React-JSS. React-JSS is a framework integration that allows you to use JSS in React applications. It’s a separate package, so you don’t need to install the JSS core, just the React-JSS package. React-JSS uses the new Hooks API to combine JSS with React.

Let’s compare JSS to the inline style.

Inline style:

import React from 'react'

const Button = () => {
  const buttonGreen = {
    backgroundColor: "green",
    border: "1px solid white",
    borderRadius: "2px"
  };

  return(
    <button style={buttonGreen}>
      green
    </button>
  )
}
Copy the code

The React – JSS:

import React from 'react'
import {createUseStyles} from 'react-jss'

const useStyles = createUseStyles({
  buttonGreen: {
    backgroundColor: "green",
    border: "1px solid white",
    borderRadius: "2px"
  }
})

const Button = () => {
  const {buttonGreen} = useStyles()

  return(
    <button className={buttonGreen}>
      green
    </button>
  )
}
Copy the code

As you can see, react-JSS has the following characteristics compared to the normal inline style:

  • Import a createUseStyles method;
  • Create a useStyles hook using the createUseStyles method.
  • Pass the style to the createUseStyles method as a parameter object;
  • The component style buttonGreen is obtained by parsing the return value of useStyles hook.
  • Pass buttonGreen to the component’s className for resolution.

So if YOU want to pass props, what’s the difference? Moving on:

Inline components:

import React from 'react'

const Button = ({backgroundColour, children}) => {
  const buttonStyles = {
    backgroundColor: backgroundColour,
    border: "1px solid white",
    borderRadius: "2px"
  };

  return(
    <button style={buttonStyles}>
      {children}
    </button>
  )
}
Copy the code

The React – JSS:

import React from 'react'
import {createUseStyles} from 'react-jss'

const useStyles = createUseStyles({
    buttonStyles: {
      backgroundColor: backgroundColour => backgroundColour,
      border: "1px solid white",
      borderRadius: "2px"
    }
})

const Button = ({backgroundColour, children}) => {
  const {buttonStyles} = useStyles(backgroundColour)

  return(
    <button className={buttonStyles}>
      {children}
    </button>
  )
}
Copy the code

The above component can be called as follows:

import React from 'react';
import Button from 'Button';

const SomePage = () => (
  <Button backgroundColour="blue">blue</Button>
)
Copy the code

The difference here is also obvious. You need to pass the props value to the useStyles method so that it can be used in createUseStyles. This is the basic use of React-JSS. Here’s a look at its pros and cons

React-jss benefits:

  • Reusability: Components are reusable, so they can be used anywhere in a single write;
  • Dynamic styles: You can use props to set styles dynamically.
  • Local scope: JSS supports local styles.

React-jss disadvantages:

  • Extra layers: Using the React-JSS library gives React applications an extra layer, which is sometimes unnecessary;
  • Code readability: Class names are also automatically generated in this way, which are unique and less readable, especially when the browser is debugging and it is difficult to determine where the style is defined.

The following describes five common React style policies. None of these five policies is absolutely good or bad. They all have advantages and disadvantages and can be used according to actual business scenarios.

Interested partners can add wechat to learn together: CUG-gz