Styling Components
Vanilla CSS (not recommended)#
![[Pasted image 20240609011302.png]]
In App.tsx
:
import ListGroup from './components/ListGroup'
== import ListGroup from './components/ListGroup/index'
CSS module#
![[Pasted image 20240609011944.png]]
Name the css file into filename.module.css
and import it in the corresponding tsx file:
import styles from "./filename.module.css"
Referencing the style like style['list-group']
. Dot notation is not allowed because the hyphen is not a valid property name in Javascript or Typescript, so we cannot access this property using the dot notation. Instead, we use squard brackets.
When using the css module, we prefer to use the camel notation like listGroup
. And by doing so, we can access the style just like the regular javascript object. styles.listGroup
For multiple class name: className = {[styles.listGroup, styles.container].join(' ')}
= class = listGroup container
CSS-in-JS (Controversial)#
![[Pasted image 20240609013325.png]]
![[Pasted image 20240609013354.png]]
npm i styled-components
`npm @types/styled-components
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
Inline Styles (Not recommended)#
Bad practice, last resort!
<ul className="list-group" style={{backgroundColor: yellow}}
named using camel casing.
Popular UI library#
- Bootstrap
- Material UI (comprehensive)
- Tailwind CSS (utility-first)
- Daisy UI (similar to Bootstrap)
- Chakra UI (built on top of tailwind, easy to learn)
React icons#
https://react-icons.github.io/react-icons/
Separation of Concerns#
![[Pasted image 20240609014452.png]]
Exercise CSS Module#
1 2 3 |
|
import styles from "./Button.module.css"
<button className = {[styles.btn, style['btn-' + color]].join(' ')} onClick={onClick}>
Exercise Like Component#
Recap: When you need to toggle the status of a component, the useState hook should be inside the component itself, not its parent component.
Toggle Function:
- The toggle
function is defined to toggle the isLiked
state between true
and false
.
- It also calls the onClick
prop function, which is passed down from the parent component.
1 2 3 4 |
|
- The
App
component renders the Like
component and passes a function as the onClick
prop. This function logs "Clicked" to the console when executed.1 |
|
This design allows the Like
component to manage its own isLiked
state internally while also triggering an external action (logging to the console) whenever the like state changes, demonstrating how child components can inform parent components of events through callbacks.
Like.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
App.tsx
1 2 3 4 5 6 7 8 |
|
2024-06-07 23:11 2024-06-09 15:38