Hướng dẫn Styled Components cơ bản

Tram Ho

styled-components xây dựng với mục tiêu giữ cho các styles của component nằm chính trong component đó

1. Cài đặt

Cách sử dụng

2. Tạo component với các thẻ html cơ bản

Output ra HTML với class được sinh ra ngẫu nhiên không bị trùng nhau

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

3. Props

Ta có thể truyền props vào các styled components như sau

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

4. Extending Styles

Kế thừa style từ component khác

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

5. Styles với các thư viện khác

Kế thừa cả những component của bên thứ 3

5-1. React router dom

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

5-2. Material MUI

Cài đặt thư viện MUI

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

5-3. Ant design

Cài đặt thư viện Antd

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

6. custom tagName

Với styled-components bạn cũng có thể thay đổi tag name so với định nghĩa ban đầu.

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

7. CSS Selector

Trong styled-components có thể sử dụng những CSS selector cơ bản như > , + , ~ …

và sử dụng Nesting như SASS

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

8. Responsive

Hoạt động tốt với 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

Kiểu 1: tạo ra button có type là submit

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

Kiểu 2: tạo ra common button, sau đó tạo submit button kế thừa từ button này

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

kiểu 3: attrs nhận vào function

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

11. Global style

Tạo ra global style áp dụng cho toàn dự án

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

12. Styled Theme

Tạo ra theme config để dùng chung

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

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo