TIL | #13 React | classnames, styled-components

trevor1107·2021년 4월 11일
0

2021-04-05(월)

classnames module

css 클래스 선택자를 조건부로 설정하거나, 여러 클래스를 적용할 때 편리함을 제공해주는 모듈이다.

모듈 설치 yarn add classnames or npm install classnames

// classnames 모듈
// css클래스를 조건부로 설정한다.
// CSS Module -> classnames 여러 클래스를 적용할 때 편리하다.

import classnames from 'classnames';
classnames('one', 'two'); // one, two
classnames('one', { two: true }); // one, two
classnames('one', { two: false }); // one

// styles.[클래스이름];

// 아래 엘리먼트의 클래스에 apple이라는 값이 true이면 apple 클래스가 적용되고, 
// false이면 적용되지 않는다.
// banana는 전달 받은 그대로 내용이 전달된다.
const MyComponent = ({ apple, banana }) => {
    <div className={classnames('MyComponent', { apple }, banana)}> </div>;
};
const MyComponent = ({ apple, banana }) => {
    <div className={`MyComponent ${banana} ${apple ? 'apple'}`}> </div>;
};
import classNames from 'classnames/bind';

// 미리 styles에서 클래스를 받아오도록 설정
const cx = classNames.bind(styles);

// <div className={`${styles.wrapper} ${styles.inverted}`}>
//     안녕?<span className="something">반가워</span>
// </div>

// classnames 모듈의 bind를 이용해서 위와 똑같은 스타일을 적용하는 문법이다.
<div className={cx('wrapper', 'inverted')}>
    안녕?<span className="something">반가워</span>
</div>

styled-components module

JavaScript에 CSS를 작성할 수 있게 해주는 인기 모듈이다.

import styled, { css } from 'styled-components';

const sizes = {
    desktop: 1024,
    tablet: 768,
};
// 위에잇는 size객체에 따라 자동으로 미디어 쿼리 함수를 만들어준다.
const media = Object.keys(sizes).reduce((acc, label) => {
    acc[label] = (...args) => css`
        @media (max-width: ${sizes[label] / 16}em) {
            ${css(...args)};
        }
    `;
    return acc;
}, {});

const Box = styled.div`
    // props로 넣어준 값을 직접 전달할 수도 있다.
    background: ${(props) => props.color || 'blue'};
    padding: 1rem;
    display: flex;

    /* width: 1024px; */
    /* margin: 0 auto; */
    /* @media ( max-width) */

    ${media.desktop`width:768px`}
    ${media.tablet`width:100%`}
`;
const Button = styled.button`
    background: white;
    color: black;
    border-radius: 5px;
    padding: 0.5rem;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    font-size: 1rem;
    font-weight: 600;
    &:hover {
        background: rgba(255, 255, 255, 0.7);
    }

    ${(props) =>
        props.inverted &&
        css`
            background: none;
            border: 2px solid white;
            color: white;
            &:hover {
                background: white;
                color: black;
            }
        `};
    & + button {
        margin-left: 1rem;
    }
`;
profile
프론트엔드 개발자

0개의 댓글