Programming/JavaScript & TypeScript

[React 라이브러리] 스타일링 라이브러리

홍열 2022. 5. 10. 15:33
728x90

css 문제점

Global Namespace, Dependencies, Dead Code Elimination

Minification, Sharing Constants .....

글로벌 변수를 지양해야하는 JS와 대치

css간의 의존관리

안쓰는 css 인지 어려움

클래스 이름 최소화

JS의 코드와 값을 공유하고 싶음 

파일 로드 타이밍 이슈

1. styled-component

자동 관리 되며, 지우기 쉽다. (css문제점 해결, 스타일을 분리)

https://styled-components.com/

 

styled-components

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅🏾

styled-components.com

예제

더보기

npm install --save styled-components

 

render method 밖에서 styled component를 정의하자 

기본 사용 방법 

import React from 'react'
import styled from 'styled-components'

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

export default function StyleComponentExample() {

return (
	<div>
    	<Wrapper>
        	<Title> Hello World </Title>
        </Wrapper>
    </div>

props도 넘겨서 적용 가능 

import React from 'react'
import styled from 'styled-components'

    const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;


export default function StyleComponentExample() {
    return (
        <div>
            <h1>StyleComponentExample</h1>
            <Button onClick={() => { alert('normal') }}>Normal</Button>
            <Button primary onClick={() => { alert('Primary') }}>Primary</Button>
        </div>

    )
}

&는 나 자신을 의미한다.

+는 바로 옆을 의미

~주변에 같은게 있는지 판단

import React from 'react'
import styled from 'styled-components'


const Thing = styled.div.attrs((/* props */) => ({ tabIndex: 0 }))`
  color: blue;

  &:hover {
    color: red; // <Thing> when hovered
  }

  & ~ & {
    background: tomato; // <Thing> as a sibling of <Thing>, but maybe not directly next to it
  }

  & + & {
    background: lime; // <Thing> next to <Thing>
  }

  &.something {
    background: orange; // <Thing> tagged with an additional CSS class ".something"
  }

  .something-else & {
    border: 1px solid; // <Thing> inside another element labeled ".something-else"
  }
`


export default function StyleComponentExample() {

  return (
    <div>
      <h1>StyleComponentExample</h1>
      <>
        <Thing>Hello world!</Thing>
        <Thing>How ya doing?</Thing>
        <Thing className="something">The sun is shining...</Thing>
        <div>Pretty nice day today.</div>
        <Thing>Don't you think?</Thing>
        <div className="something-else">
          <Thing>Splendid.</Thing>
        </div>
      </>

    </div>

  )
}

attr을 이용해서 이미 주어진 속성을 조작가능하다. 

const Input = styled.input.attrs(props => ({
  type: "text",
  size: props.size || "1em",
}))`
  border: 2px solid palevioletred;
  margin: ${props => props.size};
  padding: ${props => props.size};
`;

// Input's attrs will be applied first, and then this attrs obj
const PasswordInput = styled(Input).attrs({
  type: "password",
})`
  // similarly, border will override Input's border
  border: 2px solid aqua;
`;



export default function StyleComponentExample() {

  return (
    <div>
      <Input placeholder="A bigger text input" size="2em" />
      <br />
      {/* Notice we can still use the size attr from Input */}
      <PasswordInput placeholder="A bigger password input" size="2em" />
    </div>
  )
}

 

다른 예제들은 하나하나 확인해보면 될것 같다.

2. emotion

https://emotion.sh/docs/introduction

 

Emotion - Introduction

Emotion is a library designed for writing css styles with JavaScript. It provides powerful and predictable style composition in addition to a great developer experience with features such as source maps, labels, and testing utilities. Both string and objec

emotion.sh

css를 만들 수도 있고, styled component를 직접 만들 수도 있다. 

더보기
/** @jsxImportSource @emotion/react */
import React from 'react'
import { css } from '@emotion/react'
import styled from '@emotion/styled'

const color = 'white'

export default function EmotionExample() {
    const Button = styled.button`
  padding: 32px;
  background-color: hotpink;
  font-size: 24px;
  border-radius: 4px;
  color: black;
  font-weight: bold;
  &:hover {
    color: white;
  }
`
    return (
        <>
            <div
                css={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}
            >
                Hover to change color.
            </div>
            <br />
            <Button> This is my button compoenent</Button>

        </>
    )
}

 

fallback의 개념도 있는데, 브라우저마다 동작이 다를 수 있어 기본값을 지정하고, 문제가 생기면 대체하는 개념

(Define fallback values for browsers that don’t support features with arrays.)

 

3. sass

위에 두개랑 다르게 css를 좀 더 확장하는 개념

언어로 봐야함...

https://www.npmjs.com/package/sass

 

sass

A pure JavaScript implementation of Sass.. Latest version: 1.51.0, last published: 21 days ago. Start using sass in your project by running `npm i sass`. There are 4599 other projects in the npm registry using sass.

www.npmjs.com

preprocessing -> 전처리기..css를 생성해준다. 

확장성이 좋다..

더보기
ㅂㅈㄷ