[styled-component] mixin

Jihyun-Jeon·2022년 7월 8일
0

HTML,CSS

목록 보기
33/34

mixin 이란?

여러 컴포넌트 간에 공통으로 사용하고 있는 로직, 기능들을 재사용하는 방법.


1. variables.js 파일에 자주 사용하는 css 스타일 작성

자주 사용하는 css 스타일에 대해서는 variables.js 파일을 별도로 생성하여 사용하는게 좋음.

<사용방법1️⃣ - ThemeProvider에서 prop으로 보내는 법 >

2. ThemeProvider에서 theme prop으로 보내어 전역에서 가져다 쓸 수 있게 해줌

3. 사용 - props로 받아와서 쓰면 된다.

3-1) variables.js 파일에서 기본으로 설정한 값을 사용할 때

3-2) 다른 인자를 넘겨줄때

<사용방법2️⃣ - 각 컴포넌트에서 직접 variables를 import하는 법 >

import styled from 'styled-components';
import variables from './styles/variables';

const Test = () => {
  return (
    <Box>
     	<p>hello</p>
    </Box>
  );
};

const Box = styled.div`
  ${variables.flex()}
`;

export default Text;


✅ flex mixin 더 깔끔하게 만들기

flex mixin에서 각 매개변수에 기본값을 주었다.
기본값으로 사용할 땐 문제가 없지만 , 3번째 매개변수(align)만 변경해야 할 때
1,2번째 매개변수는 기본값을 적용하기 위해 불필요하게 undifined를 인자로 작성해 줘야했다.

1. 이전 코드

// variables.js
import {css} from "styled-components";

const variables = {
	flex : ( direction = "row" , justify = "center" , align = "center ) =>	`
	   dispaly : flex;
       flex-direction : ${direction};
	    justify-content : ${justify}; 
	    align-items : ${align}; 
 	 `
}

// index.js
import variables "./variables.js"

// 1. 기본값으로 실행시
const Box = styled.div`
       ${variables.flex()} `;

// 2. direction만 바꿀시 
const Box = styled.div`
       ${variables.flex("column")} `;

// 3. align만 바꿀시  // 문제✅ - 불필요한 undifined를 써줘야 한다.
const Box = styled.div`
       ${variables.flex(undifined , undifined , "end" )} `; 	
                   

2. 리팩토링 코드

1) flex의 매개변수를 객체로 받도록 하였고, 객체의 키값이 없는 속성은 기본값을 적용하도록 하였다.

2) 과정
처음에 obj.direction으로 하니까 오류가 났었다.
Uncaught TypeError: Cannot read properties of undefined (reading 'direction')

그 이유는 obj가 없을경우 obj는 undifined가 되는데
그럼 undifined.direction를 찾게되어서 여기서 오류가 나기 때문이다.
그래서 옵셔널 체이닝(?.)을 이용하여 obj가 없으면 .direction를 찾지말고 바로 undifined가 나오게끔 하였다.

// variables.js
import {css} from "styled-components";

const variables = {
	flex : obj =>	`
	   dispaly : flex;
       flex-direction : ${obj?.direction ?? "column"};
	    justify-content : ${obj?.justify ?? "center"}; 
	    align-items : ${obj?.align ?? "center"}; 
 	 `
}

// index.js
import variables "./variables.js"

// 1. 기본값으로 실행시
const Box = styled.div`
       ${variables.flex()} `;

// 2. direction만 바꿀시 
const Box = styled.div`
       ${variables.flex( {direction : "row"} )} `;

// 3. align만 바꿀시  // 문제해결✅ - 불필요한 인자를 보내지 않아도 기본값이 적용된다.
const Box = styled.div`
       ${variables.flex( {align:"end"} )} `; 	
        


✅ variables.js 더 깔끔하게 만들기

하나의 객체형태의 변수에 모든 mixin 코드들을 담아서 사용할 수도 있지만,
이렇게 mixin코드를 각각 변수로 만들어 사용하는게 좋다.
그래야 나중에 빌드할 때 안쓰는 변수는 빌드처리 안되기 때문에, 코드를 더 압축할 수 있어서

import { css } from 'styled-components';

export const flex = obj => `
  display: flex;
  flex-direction: ${obj?.direction ?? 'row'};
  justify-content: ${obj?.justify ?? 'center'};
  align-items: ${obj?.alignItem ?? 'center'};  
  `;

export const absoluteCenter = css`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
`;

// 이후 사용시 - 각각import해서 가져와 사용해야 한다.

0개의 댓글