컴포넌트 스타일링의 또 다른 패러다임은 자바스크립트 파일 안에 스타일을 선언하는 방식입니다.
이 방식을 'CSS-in-JS' 라고 부릅니다.
여기서는 CSS-in-JS 라이브러리 중에서 개발자들이 가장 선호하는 styled-components를 알아보겠습니다.
먼저 styled-components를 설치해보겠습니다
npm install styled-components
styled-components 라이브러리를 사용하면 자바스크립트 파일 하나에 스타일까지 작성할 수 있기 때문에
.css 또는 .scss 확장자를 가진 파일을 따로 생성하지 않아도 된다는 큰 이점이 있습니다.
// StyledComponent.js
import styled, { css } from "styled-components";
const Box = styled.div`
/* props로 넣어 준 값을 직접 전달해 줄 수 있습니다 */
background: ${props => props.color || 'blue'};
padding: 1rem;
display: flex;
`;
const Button = styled.button `
background: white;
color: black;
border-radius: 4px;
padding: 0.5rem;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
font-size: 1rem;
font-weight: 600;
/* &문자를 사용하여 Sass처럼 자기 자신 선택 가능 */
&:hover{
background: rgba(255,255,255, 0,9);
}
/* 다음 코드는 inverted 값이 true일때 특정 스타일을 부여해 줍니다. */
${props =>
props.inverted &&
css`
background: white;
border: 2px solid white;
color: black;
&:hover {
background: black;
color: white;
}
`};
& + button {
margin-left: 1rem;
}
`;
const StyledComponent = () => {
return (
<Box color="black">
<Button>안녕하세요</Button>
<Button inverted={true}>테두리만</Button>
</Box>
);
};
export default StyledComponent;
작성한 컴포넌트를 App.js에 렌더링해줍니다.
위의 코드를 보면 CSS의 코드에 킨텍스 하이라이팅이 제대로 이루어지지 않는 것을 볼 수 있습니다.
문법에 따라 에디터의 폰트에 색상을 입히는 작업
예시)
이를 위해 vs code의 마켓 플레이스에서 vscode-styled-components를 검색하여 설치해봅시다.
확장 프로그램을 설치하면
킨텍스 하이라이팅이 제대로 적용되는 것을 볼 수 있습니다.