For the Styled Components, I’ve been thinking about how to split the React component until I came across the Styled Components, and I’m going to share with you today how the library makes our front-end component development more elegant and how to maintain a more appropriate component separation granularity for easier maintenance.

First, use method

Styled – Components is a library tailor-made for React. Styled – Components follows the all in JS design concept of React and further develops this concept to the extreme, allowing CSS to become JS modules.

It’s also pretty easy to use, so install the library first

npm install styled-components --save
Copy the code

Then use it in style.js (note that this is not style.css, style files are all JS files)

import styled from 'styled-components';
//styled. XXX specifies that the H5 tag XXX is created,
// The following string contains the CSS code
export const HeaderWrapper = styled.div` z-index: 1; position: relative; height: 56px; border-bottom: 1px solid #f0f0f0; `;
Copy the code

Then use it in React:

import React, {Component} from 'react';
import { HeaderWrapper } from './style.js';

class App extend Component{
    render() {
        return (
            <HeaderWrapper></HeaderWrapper>
        )
    }
}
export default App;
Copy the code

Ok! That’s how it’s used on a daily basis. If you are interested, go to the github repository to open up more postures

Styled – Component is used to address the pain points

You may wonder: What’s the good of this?

1. The CSS modular

The coupling degree between modules should be reduced as far as possible to facilitate the further maintenance of the project. This is the first advantage over using native CSS.

2. Support preprocessor nested syntax

Such as:

export const SearchWrapper = styled.div`
  position: relative;
  float: left;
  .zoom {
    right: 5px;
    &.focused {
      background: # 777;
      color: #fff;}} `;Copy the code

Can use sASS,less nested syntax, development is more smooth.

3. Let CSS code handle logic

Not only can the template string be used to write JAVASCRIPT expressions, but it is also important to get the context information of the component (state, props).

For example, the JSX code in the React component reads:

<RecommendItem imgUrl={'xxx'} / >Copy the code

The corresponding argument can be accepted in the corresponding style.js:

export const RecommendItem = styled.div`
  width: 280px;
  height: 50px;
  background: url(${(props) => props.imgUrl});
  background-size: contain;
`;
Copy the code

Isn’t it cool that CSS can take the content in props and render it accordingly?

4. The semantic

If that doesn’t add up, it’s poison for front-end developers.

A lot of people are jumping at the idea of semantic tags, but most developers are just div+class. Is it because semantics are bad? To make labels easier to understand, of course, is a good thing, but for the HTML 5 specification label, on the one hand slightly cumbersome for developers, or div, span, h1 is more simple and kind, on the other hand, after all, is a standard, it does not represent the business, so do not expressive enough to describe the numerous and complicated business, Even this semantization is sometimes optional. I think both of these are the root reasons why developers prefer div+class handouts.

Well, with React component development in mind, what if you want to get more expressive and as semantic as possible? You may chuckle: this is also said, dismantling components ah! But are components really as thin as possible?

Someone once said: As you break down the components into smaller pieces, you find that each component is a label. But this can cause more serious problems. Assuming that we are disassembling all UI components, when we wrap even a button into a component for semantic purposes, the code will become bloated because there will be too many components, which is very difficult to maintain.

So, is there a compromise? It can not only improve the semantics of tags, but also control the number of JS files. Yes, the scheme is styled- Components.

Taking the navigation on the home page as an example, JSX looks like this after fetching the logic:

<HeaderWrapper>
    <Logo/>
    <Nav>
        <NavItem className='left active'> </NavItem> <NavItem className='left'> Download App</NavItem> <NavItem className='right'>
            <i className="iconfont"> &#xe636; 
    	</NavItem>
        <SearchWrapper>
            <NavSearch></NavSearch>
            <i className='iconfont'> &#xe614; 
        </SearchWrapper>
    </Nav>
    <Addition>
        <Button className='writting'>
    	  <i className="iconfont"> &#xe615; </Button> <Button className='reg'</Button> </Addition> </HeaderWrapper>Copy the code
//style.js
import styled from 'styled-components';

export const HeaderWrapper = styled.div` z-index: 1; position: relative; height: 56px; border-bottom: 1px solid #f0f0f0; `;

export const Logo = styled.div`
    position: absolute;
    top: 0;
    left: 0;
    display: block;
    width: 100px;
    height: 56px;
    background: url(${logoPic});
    background-size: contain;
`;

export const Nav = styled.div` width: 960px; height: 100%; padding-right: 70px; box-sizing: border-box; margin: 0 auto; `;
/ /...
Copy the code

In this case, the CSS becomes a JS module, and each module acts as a tag (for example, styled. Div has already created the tag for us). You can write the H5 tag under the module. This approach to development is actually very flexible.

Third, the pit encountered in the development process and the current shortcomings

Pit: The previous injectGlobal has been deprecated, so createGlobalStyle is needed for global style files to be introduced.

//iconfont.js
// Same for global styles
import {createGlobalStyle} from 'styled-components'

export const IconStyle = createGlobalStyle` @font-face { font-family: "iconfont"; src: url('./iconfont.eot? t=1561883078042'); /* IE9 */ src: url('./iconfont.eot? t=1561883078042#iefix') format('embedded-opentype'), /* IE6-IE8 //... } .iconfont { font-family: "iconfont" ! important; font-size: 16px; font-style: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } `
Copy the code

Then inside the global root component app.js:

import { IconStyle } from './statics/iconfont/iconfont'
import { GlobalStyle } from  './style'
//import ...

function App() {
  return (
    <Provider store={store}>
      <div>{/* Introduce these styles as tags */}<GlobalStyle></GlobalStyle>
        <IconStyle></IconStyle>
        <Header />
        <BrowserRouter>
        <div>
          <Route path='/' exact component={Home}></Route>
          <Route path='/detail' exact component={Detail}></Route>
        </div>
        </BrowserRouter>
      </div>
    </Provider>
  );
}

export default App;
Copy the code

For styled- Components, the only drawback I see so far is that there is no CSS syntax in the template strings and no autoprompt for writing, which is still a fly in the face for those who are used to IDE prompts. However, it is not too much of a problem, if there are plug-ins or tools to share in the comments section.

For styled- Components and componentization, a few thoughts will be written down for inspiration.