※ 강의를 듣고 제가 이해한 내용을 바탕으로 정리한 것이라서 오류가 있을 수 있습니다.
styled-components 버튼 사이즈 조정하기
components/Button.js
import React from 'react';
import styled, { css } from 'styled-components';
import { darken, lighten } from 'polished'; // polished의 darken, lighten 함수 불러옴
const StyledButton = styled.button`
/* 공통 스타일 */
display: inline-flex;
outline: none;
border: none;
border-radius: 4px;
color: white;
font-weight:bold;
cursor: pointer;
padding-left: 1rem;
padding-right: 1rem;
/* 크기 */
${props => /* size props를 설정 */
props.size === 'large' &&
css`
height: 3rem;
font-size: 1.25rem;
`}
${props =>
props.size === 'medium' &&
css`
height: 2.25rem;
font-size: 1rem;
`}
${props =>
props.size === 'small' &&
css`
height: 1.75rem;
font-size: 0.875rem;
`}
/* 색상 */
${props => {
const color = props.theme.palette[props.color];
return css`
background: ${color};
&:hover {
background: ${lighten(0.1, color)};
}
&:active {
background: ${darken(0.1, color)};
}
`;
}}
/* 버튼 간의 간격 */
& + &{
margin-left: 1rem;
}
`;
function Button({ children, color, size, ...rest }) {
return <StyledButton color={color} size={size} {...rest}>{children}</StyledButton>;
}
export default Button;
위 코드와 같이 size props를 설정해준다.
App.js
import React from 'react';
import styled, { ThemeProvider } from 'styled-components'; // ThemeProvider를 사용하면 styled-components를 사용하는 모든 컴포넌트에서 색상을 지정할 수 있다.
import Button2 from './components/Button';
const AppBlock = styled.div`
width: 512px;
margin: 0 auto;
margin-top: 4rem;
border: 1px solid black;
padding: 1rem;
`;
const ButtonGroup = styled.div` /* 버튼 간의 간격을 줌 */
& + & {
margin-top: 1rem;
}
`;
const palette = {
blue: '#228be6',
gray: '#496057',
pink: '#f06595'
};
function App() {
return (
<ThemeProvider theme={{palette}}> {/* ThemeProvider 사용 */}
<AppBlock>
<ButtonGroup>
<Button color="blue" size="small">BUTTON</Button>
<Button color="pink" size="medium">BUTTON</Button>
<Button color="gray" size="large">BUTTON</Button>
</ButtonGroup>
</AppBlock>
</ThemeProvider>
);
}
export default App;
App.js에서 Button 컴포넌트를 불러와 준다.
'개발 공부한 내용 정리 > React' 카테고리의 다른 글
React- Dialog 만들기 (0) | 2020.10.13 |
---|---|
React- styled-components 버튼 outline, fullWidth (0) | 2020.10.12 |
React- polished의 스타일 관련 유틸 함수 사용하기 (0) | 2020.10.10 |
React- styled-components로 버튼 만들기 (0) | 2020.10.09 |
React- styled-components (0) | 2020.10.08 |