Skip to main content

[dB's 리액트] Styled Components_ 기본개념

컴포넌트 제작
1. Small, focussed component
2. Container component

class Sidebar extends React.Component {
    componentDidMount() {
     fetch('api.com/sidebar')
      .then(res => {
       this.setState({
        items: res.items
       })
      });
    }

    render() {
     return (
      <div className="sidebar">
       {this.state.items.map(item => (
        <div className="sidebar__item">{item}</div>
       ))}
      </div>
     )
    }
}
Containers와 components를 분리합니다. Containers는 작동원리를 포함하고, components는 어떻게 보이는지를 나타냅니다.

class SidebarContainer extends React.Component {
 componentDidMount() {
  fetch('api.com/sidebar')
   .then(res => {
    this.setState({
     items: res.items
    })
   });
 }

 render() {
  return (
   <Sidebar>
    {this.state.items.map(item => (
     <SidebarItem item={item} />
    ))}
   </Sidebar>
  )
 }
}
그렇다면 스타일링은 어떨까요?
1. Single-use classes
2. Components as a styling construct

Styled-components에서 가장 중요한 것은 styles과 components의 맵핑을 제거한 것입니다. 굳이 한 번의 클래스명을 사용한다면 맵핑이 필요없기 때문입니다.

import styled from 'styled-compoents';

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

const Wrapper = styled.section`
 color: blue;
 padding: 4em;
 width: 100%;
 height: 100%;
 background: yellow;
`;

const App = () => (
 <Wrapper>
  <Title>
   Hello ReactJS!
  </Title>
 </Wrapper>
);

ReactDOM.render(
 <App />,
 document.getElementById('#app')
);
css 사용이 가능하며, props에 따라 스타일 분기가 가능합니다.

<Button>Normal</Button>
<Button primary>Primary</Button>

const Button = styled.button`
 background: ${(props) =>
  props.primary ? 'blue' : 'green'
 };
 color: ${(props) => 
  props.primary ? 'white' : 'red'
 };

 font-size: 1em;
 margin: 1em;
`;
필요에 따라 전역 스타일로도 사용이 가능하며 필요한 수 만큼 생성할 수 있습니다.

import { ThemeProvider } from 'styled-components';

const theme = {
 primary: 'blue',
};

const App = () => (
 <ThemeProvider theme={theme}>
  <Root />
 </ThemeProvider>
);

import styled from 'styled-components';

const Button = styled.button`
 background: ${props => props.theme.primary};
 color: white;
`;
참고자료
  • https://codeburst.io/how-to-style-react-components-with-styled-component-3e4db2455717

Comments

Popular posts from this blog

[dB's CSS 모듈] 리액트 컴포넌트 스타일링 (CSS Modules & React Component)

리액트 프로젝트에서 컴포넌트를 스타일링 할 때 자주 사용하는 방법으로는 아래 3가지가 있습니다. 이번 포스팅에서는 CSS 모듈에 대해 알아보도록 하겠습니다. 1. CSS Module 2. Sass 3. styled-components import withStyles from 'isomorphic-style-loader/lib/withStyles' import * as s from './Header.scss' import 된 Headers.scss 는 s 객체로 변환되며, key와 value값으로 클래스명에 접근하게 됩니다. { apply: "Businesses-apply-bc84", btn-choice: "Businesses-btn-choice-c57b", cell: "Businesses-cell-c929", root: "Businesses-root-c558" } 리액트에서 명명된 스타일 객체에 접근하려면 아래와 같이 사용할 수 있습니다. (자바스크립트 객체값 접근 방법). key값이 캐밥스타일(kebab-case)로 이루어져 있다면, 오류를 줄이고자 작은따옴표를 사용하는 것을 권장 합니다. <div className={s.item}></div> <button className={s['btn-wide']}></button> CSS 스타일 로더를 사용하는 이유는 CSS 랜더링 및 동일구조 앱 환경 최적화를 목표로 하고 있습니다. Isomorphic Javascript 앱은 클라이언트와 서버 사이드 모두에서 작동되는 것을 말합니다. 이러한 앱을 만들려면 가장 중요한 것이 바로 추상화입니다. 즉, 의존성을 제거하고 어디서든 사용할 수 있도록 각각의 기능과 역할에만 집중해야 합니다. CSS 스타일도 마찬가지 입니다. CSS Modules 좀 더 자세히 알아보기 CSS 모듈은...

[dB's 몽고DB] MongoDB 데이터베이스 사용하기

오라클, MySQL 을 관계형 데이터베이스 라고 합니다. 이는 데이터를 담고 있는 복수 개의 테이블들이 긴밀하게 연결되어 있기 때문입니다. 이와 다르게, 몽고DB는 NoSQL 입니다. "SQL이 필요없다"가 아니라 "비관계형 데이터베이스 SQL" 이라는 뜻을 내포하고 있습니다. 이유는, DB에 접근하기 위해서는 결국 몽고DB에서 사용하는 쿼리문법이 필요하기 때문입니다. 특별히, 몽고DB는 자바스크립트 객체를 그대로 저장할 수 있어서 자바스크립트를 사용하는 노드에서 데이터를 저장하기에 적합합니다. 그렇기 때문에 데이터 저장, 조회 방식도 기존 SQL과 다릅니다. 이는 성능을 최우선으로 생각하기 때문에 고안된 방법이며 실시간 서비스나 대용량 트래픽을 감당할 수 있는 메시징 시스템등에 사용됩니다. 몽고DB는 데이터베이스의 테이블 대신, 여러 데이터가 모인 컬렉션(Collection)을 사용합니다. 즉, 데이터베이스는 컬렉션의 집합이고 각각의 컬렉션은 여러개의 문서객체(Document)를 가질 수 있습니다. 1. 몽고DB 설치하기 몽고DB 다운로드 센터로 이동 Installing with Homebrew 몽고DB 설치 brew install mongodb 데이터베이스 저장 폴더 만들기 mkdir -p /data/db 권한 부여하기 chown $USER /data/db 몽고DB 활성화가 되면서 27017 포트에서 연결을 기다린다는 메시지가 표시됨   mongod 몽고Shell 접속하기 새로운 터미널에서 mongo 2. 데이터베이스 생성과 입력, 삭제 데이터베이스 지정 use local 컬렉션 만들기 db.users.insert({name: '소녀시대'}) 컬렉션 문서조회 db.users.find().pretty() 문서삭제 d b.users.remove({name:/소녀시대/}) 로그인에 필요한 데이터 입력 db.users.insert({id: 'tes...