컴포넌트 제작
1. Small, focussed component
2. Container component
1. Single-use classes
2. Components as a styling construct
Styled-components에서 가장 중요한 것은 styles과 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
Post a Comment