Basic Styled Components Tutorial

Tram Ho

styled-components is built with the goal of keeping the component’s styles in that component

1. Settings

Using

2. Create components with basic html tags

Output to HTML with a randomly generated class that does not overlap

Demo: https://codesandbox.io/s/styled-component-html-220lyc?file=/src/App.js

3. Props

We can pass props to styled components as follows:

Demo: https://codesandbox.io/s/styled-components-props-zh1092?file=/src/App.js

4. Extending Styles

Inherit style from another component

Demo: https://codesandbox.io/s/styled-components-extend-style-q6tq0c?file=/src/App.js

5. Styles with other libraries

Inherit 3rd party components

5-1. React router dom

Demo: https://codesandbox.io/s/styled-component-react-router-dom-28oebw?file=/src/App.js

5-2. Material MUI

Install MUI library

Demo: https://codesandbox.io/s/styled-component-material-ui-r3gplj?file=/src/App.js

5-3. Ant design

Install the Antd . library

Demo: https://codesandbox.io/s/styled-component-antd-j8j2q1?file=/src/App.js

6. custom tagName

With styled-components you can also change the tag name from the original definition.

Demo: https://codesandbox.io/s/styled-component-change-html-1fg2cl?file=/src/App.js

7. CSS Selector

In styled-components you can use basic CSS selectors like > , + , ~ …

and use Nesting like SASS

Demo: https://codesandbox.io/s/styled-component-css-selector-x7g98s?file=/src/App.js

8. Responsive

Works well with responsive

Demo: https://codesandbox.io/s/styled-component-responsive-n77075?file=/src/App.js

9. Animations

Demo: https://codesandbox.io/s/styled-component-animation-0ogv50?file=/src/App.js

10. With attribute

Style 1 : create a button with type submit

Demo 1: https://codesandbox.io/s/styled-component-attribute1-lsy7yb?file=/src/App.js

Style 2 : create common button, then create submit button inherit from this button

Demo 2: https://codesandbox.io/s/styled-component-attribute2-8pettq?file=/src/App.js

type 3 : attrs receive function

Demo 3: https://codesandbox.io/s/styled-component-attribute3-hxs2nl?file=/src/App.js

11. Global style

Create a global style that applies to the entire project

Demo: https://codesandbox.io/s/styled-component-global-style-8jyog9?file=/src/App.js

12. Styled Theme

Create theme config for sharing

Demo: https://codesandbox.io/s/styled-component-config-theme-n3ey3k?file=/src/App.js:0-836

Share the news now

Source : Viblo