-
React - CSS ModulesReact/Style 2021. 6. 5. 23:21
https://create-react-app.dev/docs/adding-a-css-modules-stylesheet
- CSS Module
- CSS 클래스가 중첩되는 것을 방지
- CSS 파일의 확장자를 .module.css 로 생성
- CSS Module 적용
// App.js import logo from './logo.svg'; import styles from './App.module.css'; import Button from './components/Button'; function App() { return ( <div className={styles['App']}> <header className={styles['header']}> <img src={logo} className={styles['logo']} alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <Button>Button</Button> </header> </div> ); } // Button.jsx import React from 'react'; import styles from './Button.module.css'; const Button = (props) => <button className={styles['button']} {...props} />; export default Button;
// Button.module.css .button { background: transparent; border-radius: 3px; border: 2px solid palevioletred; color: palevioletred; margin: 0 1em; padding: 0.25em 1em; font-size: 20px; }
- classnames 라이브러리
- 적용해야 할 CSS가 여러개일 경우 번거로움 발생
- classnames 라이브러리 사용
- npm i classnames
.button { background: transparent; border-radius: 3px; border: 2px solid palevioletred; color: palevioletred; margin: 0 1em; padding: 0.25em 1em; font-size: 20px; } .loading { border: 2px solid grey; color: grey; }
import React from 'react'; import styles from './Button.module.css'; import classNames from 'classnames/bind'; const cx = classNames.bind(styles); class Button extends React.Component { state = { loading: false, }; render() { const { loading } = this.state; return ( <button onClick={this.startLoading} className={cx('button', { loading })} {...this.props} /> ); } startLoading = () => { this.setState({ loading: true, }); setTimeout(() => { this.setState({ loading: false }); }, 1000); }; } export default Button;
'React > Style' 카테고리의 다른 글
Ant Design (0) 2021.06.06 React - Shadow (0) 2021.06.06 React - Styled Components (0) 2021.06.06 React - Style Loaders (0) 2021.06.05 - CSS Module