처음 사용하는 styled-Component

김범식·2023년 4월 11일
0
post-thumbnail

styled - Component

최종 편집 일시: 2023년 4월 11일 오후 1:38
카테고리: [FE]

정의


이미 스타일이 적용된 컴포넌트






기존코드와 차이점

기존코드

const ReactButton = (props) =>{
	const style = {
		color:'white',
		backgroundColor : 'purple',
	}
return <button style = {style}> {props.children} </button>

기존코드는 style을 따로만들어서 적용시키는 방식을 채택했다. 스타일을 관리할 수 있다는 관점에서는 편리하지만 스네이크 케이스를 억지로 카멜케이스 문법으로 바꿔야한다는 단점이 있다.





styled Component

import styled from 'styled-component';

const StyledButton = styled.button` //이부분은 백틱이다. 
	color : whilte;
	background-color:purple;
`;

return <StyledButton></StyledButton>

styled에서 사용할 button을 꺼내온뒤 미리 스타일을 지정해 주는 방법이다. 장점은 기존 css문법을 그대로 사용할 수 있다는 점이다.

스타일은 html css javascript로 새롭게 class가 정의되어 빌드되게 된다.





스타일 상속받기

import styled from 'styled-component';

const SimpleButton = styled.button`
	color:white;
	background-color:green;
`;
const LargeButton = styled(SimpleButton)` //이부분에서 상속을 받아 사용할 수 있다. 
	font-size:50px;
`

function App(){
	return(
		<div>
			<SimpleButton>simple</SimpleButton>
			<LargeButton>Large</LargeButton>
		</div>
};
}

export default App;

largeButton은 simpleButton을 상속받아 이어서 사용할 수 있다. 같은 컴포넌트는 늘 재활용 되기 때문에 한번 스타일을 정해두면 편하게 사용할 수 있다. mui도 이와같은 방식이라고 생각하면 된다.





일반적인 컴포넌트 스타일주기

import styled from 'styled-component';

const SimpleButton = styled.button`
	color:white;
	background-color:green;
`;
const LargeButton = styled(SimpleButton)` //이부분에서 상속을 받아 사용할 수 있다. 
	font-size:50px;
`

const ReactButton = (props) =>{
	return <button className={props.className}>{props.children}</button>
}
const ReactLargeButton = styled(ReactButton)`
	font-size:50px;
`

function App(){
	return(
		<div>
			<SimpleButton>simple</SimpleButton>
			<LargeButton>Large</LargeButton>
			<ReactButton>React</ReactButton>
			<ReactLargeButton>React Large</ReactLargeButton>
		</div>
};
}

export default App;

일반적인 컴포넌트에 styledComponent를 적용시키려면 propsclassName을 특정지어 주어야 한다. 그래야 styled가 상속받아올 때 해당 className을 인지하고 적용할 수 있기 때문이다 아무것도 없으면 font-size:50px를 적용시키더라도 갈곳이 없는 스타일은 공중분해 된다.





동적으로 바뀌는 스타일

import styled from 'styled-component';

const SimpleButton = styled.button`
	color:white;
	background-color:green;
`;
const LargeButton = styled(SimpleButton)` //이부분에서 상속을 받아 사용할 수 있다. 
	font-size:50px;
`

const ReactButton = (props) =>{
	return <button className={props.className}>{props.children}</button>
}
const ReactLargeButton = styled(ReactButton)`
	font-size:50px;
`

//primary :true 라고 key:value가 내부적으로 생긴다.
const PrimaryButton = styled.button`
	color:$(function(props){
		console.log(props.primary)
		if(props.primary){
			return 'white';
		}else{
			return 'black';
		}
	}
`

//간결하게 만든 코드 
const PrimaryButton = styled.button`
	color: ${props => props.primary? 'white' : 'black'}
	background: ${props => props.primary? "blue" : "gray"}
`

function App()
	return(
		<div>
			<SimpleButton>simple</SimpleButton>
			<LargeButton>Large</LargeButton>
			<ReactButton>React</ReactButton>
			<ReactLargeButton>React Large</ReactLargeButton>

			<PrimaryButton>Normal</PrimaryButton>
			<PrimaryButton primary>Normal</PrimaryButton> //primary라는 prop을 주면 색이 변경되도록 할것
	
		</div>
};
}

export default App

내가 원하는 조건에 따라 버튼의 색상을 변경하는 코드를 만들었다. 3항연산자를 이용해서 styled-component 내부여 위치시켰다. if 를 사용하는것보다 가독성이 높은것을 알 수 있다.







느낀점

리액트를 사용하면서 Tailwind 를 사용할지 styled-component를 사용지 많은 고민이 있었다. 결과적으로 나에게 아주 잘 맞았고, 기존 css코드를 그대로 사용할 수 있다는점에 굉장히 마음에 들었다. 또 상속을 통해 스타일의 재사용도 가능해서 중복되는코드를 최소화할 수 있었다.

profile
frontend developer

0개의 댓글