-
[React] Styled component프론트앤드/[React] 2023. 2. 26. 15:21728x90
Styled component를 자습했다...
솔직히.. 왜쓰는지 모르겠다.
가장 최근 5년간 가장 인기있는 라이브러리라는데... 왜..? ..
다 이유가있겠지... 일단 내 손에 안익어서 그런가보다 하고...
그냥 냅다 정리부터 해본다. ㅠ
현업에서 일하는 친구도 스타일 컴포넌트를 쓴다고 한다..
일단 className을 지정안해도 되고 손에익으면 너무 편리하다고하는데..?
공부나하자..ㅠ
Styled Component
css, Sass에서는 별도의 css, sass 파일을 생성하여 js파일에 import해서 사용했지만, 스타일드 컴포넌트는 스타일링을 할 때 ES6의 Tagged Templeate Literal 문법을 이용하여 js파일 안에서 선언해서 사용할 수 있다.
적용 방법 : styled 객체에 Tagged Templete 문법을 활용해서 css속성을 정의하면 된다.
const [컴포넌트명] = styled.[html태그]`
[부여하고자 하는 css속성]
`;일단 그전에 ,
js 파일에서는 css 속성 작성할 때 자동완성이 안떠서... 불편하더라..
자동완성의 달달한 맛에 빠져버린 나는 먼저 설치하고 시작하겠다 !
설치 : vscode-styled-components
이제 적용해 보자
예시)
// App.js import React from 'react'; import styled from 'styled-components'; // 1 const App = () => { return <Title>styled-components!!</Title>; // 2 }; const Title = styled.h1` ⌉ font-size: 32px; | text-align: center; | // 3 color: purple; | `; ⌋ export default App;
1. styled-components를 사용하기 위해서 styled 를 import 해 준다.
2. UI가 그려지는 return문 안에서 html태그가 갖고 있는 속성을 스타일드 컴포넌트로 선언한 컴포넌트에도 적용이 가능하다.
& 선택자
import styled from 'styled-components'; const Button = styled.button` background-color: #6750a4; border: none; color: #ffffff; padding: 16px; &:hover, &:active { background-color: #463770; } `; export default Button;
컴포넌트를 호버하거나 클릭했을 때 배경색이 바뀌게 하고싶을때 &:hover, &:active 를 이용했다.
css에서는 다음과 같이 쓸 수 있다.
.Botton:hover { }
진짜그냥 sass 가 더 나은것같은데..아직까진,ㄴ.. ㅠ_ㅠ 모르겠자너..?
컴포넌트 선택자
위에서와 같이 보라색 버튼 안에 네일 아이콘 + Hello Styled 라고 되어있다.
이처럼 컴포넌트 안에 또다른 컴포넌트를 선택하고자 한다면 어떻게 해야할깡?ㅇ?
Icon 과 StyledButton 컴포넌트를 각각 만들고
StyledButton안에 Icon 컴포넌트를 넣어줄 예정이다.
import styled from 'styled-components'; import nailImg from './nail.png'; const Icon = styled.img` width: 16px; height: 16px; `; //Icon 컴포넌트 선언 const StyledButton = styled.button` background-color: #6750a4; border: none; color: #ffffff; padding: 16px; //StyledButton 스타일 선언 & ${Icon} { margin-right: 4px; } //Icon 컴포넌트를 넣어줌 &:hover, &:active { background-color: #463770; } `; //마우스를 올렸을때, 클릭했을때 function Button({ children, ...buttonProps }) { return ( <StyledButton {...buttonProps}> <Icon src={nailImg} alt="nail icon" /> {children} </StyledButton> ); } export default Button;
이처럼 컴포넌트를 선택자로 쓰고 싶을 때에는
${Icon}같이 컴포넌트 자체를 템플릿 리터럴 안에 넣어주면 된다.
바로 2차 프로젝트때부터 sass가 아닌 이 styled component를 사용해야 해서..
기초적인것 정리를 해보았다만..
음..아직까지 className 따로 부여안해도되는것 밖에 모르겠당...!!!
계속 사용하면서 연습해보고 바로바로 써보면서 알아가야겠다 ... 😂
728x90'프론트앤드 > [React]' 카테고리의 다른 글
[React] 카카오 API 연결 로그인 (0) 2023.02.28 [React] Styled component (props) 1-2 (적용) (0) 2023.02.26 [React] useState 조건부 렌더링 (0) 2023.02.22 [React] useState (count하기, 비동기) (0) 2023.02.22 [React] scss안에서 다른 scss파일 부르기, scss @mixin , 변수 이용 (0) 2023.02.22