목차
목차1. React Day31. Text 컴포넌트 만들기 with storybook2. Header 컴포넌트 with storybook3. Image 컴포넌트 with storybook4. Spinner 컴포넌트 with Storybook5. Toggle 컴포넌트 with Storybook
1. React Day3
1. Text 컴포넌트 만들기 with storybook
[ 기본 ]
children
,props
,args
를 통해 확장 가능한 컴포넌트를 만들 수 있다.
[ 추가 가능한 props ]
- block, paragraph 를 통한 Tag 지정
const Tag = block ? "div" : paragraph ? "p" : "span";
- size, color, weight, underline 등의 textStyle 지정
- del, mark, code 등의 지정되어 있는 styleTag 사용
if (mark) { children = <mark>{children}</mark> }
[ className 을 통해 css 적용하기 ]
- CSS에 classname을 미리 지정해두고 다양한 case를 만들어 컴포넌트를 만들어 낼 수 있다.
[ 코드예시 ]
보기
// Text.stories.js export const Size = (args) => { return ( <> <Text {...args} size="small"> Text </Text> <Text {...args} size="noraml"> Text </Text> <Text {...args} size="large"> Text </Text> <Text {...args} size={50}> Text </Text> </> ); }; // Text.js ... <Tag className={typeof size === "string" ? `Text--size-${size}` : undefined} style={{ ...props.style, ...fontStyle }} {...props}> {children} </Tag>
2. Header 컴포넌트 with storybook
- storybook에서 범위값 지정하기
- 객체로 control 타입을 열고, type: “range”, min, max 값으로 범위 지정하기
- Header는 h1 ~ h6 까지만 존재
argTypes: { level: { control: { type: "range", min: 1, max: 6 } }, }
3. Image 컴포넌트 with storybook
[ props ]
- 필수
- src, width, height, alt
- 추가
- mode
- mode는 css의 objectFit 속성에 지정가능한 값으로,
cover, fill , contain
3가지 중 사용가능 - cover: 그림의 원본 유지하며 해당 부분 덮게 됨
- fill: 그림이 짤리지 않도록, 크기에 따라 변경
- contain: 그림이 width만큼의 비율만 유지하도록 자름
- block
- display 속성을 block으로 설정
[ 스토리북에서 argTypes 속성 활용]
- control 이외에도, 다양한 속성을 통해 스토리북 활용 가능
name
: 기본 속성이름 말고 custom한 이름값을 지정type.require
: 해당 속성의 필수 여부 지정defaultValue
: 해당 속성의 기본 값 지정options
: radio나 checkbox등을 설정한 값들을 배열형태로 작성control: {type: ‘inline-radio’}
등과 함께 사용
[ 스토리북에서 Image의 lazy-loading 적용하기]
- intersection Observer 개념 (링크)
- 흐름
- observer 선언
- observer에 new IntersectionObserver( callback, options) 생성하여 할당
- callback 함수
onIntersection()
- 타겟 요소의 관찰이 시작되거나, 가시성에 변화가 감지되면(
threshold
와 만나면) 등록된callback
이 실행 - 콜백함수는 메인스레드에서 처리
- 가시성 변화가 감지될 때 마다, 해당 entry의 특정 동작 상황을 지정하고, 해당 상황에 특정 동작을 실행하도록 함
적용
entry.isIntersection
즉 루트노드(viewport), 타겟요소(img)가 threshold 이상의 교차가 발생하면 관찰을 중단하고, customEvent를 발생시킨다.- options
threshold
: 루트노드와 타겟요소의 교차정도를 지정 (0.5 = 50%)- 생성된 observer가 imgRef.current에 해당하는 img요소(타겟요소)를 관찰하도록 함
- customEvent를 타겟요소에 등록해줌
- intersectionObserver가 특정 가시성 변화를 읽어, customEvent를 발생하면, 이를 타겟요소에서 캐치하여, handleLoadImage()를 실행시킴
handleLoadImage
는 현재 타겟요소의 이미지를 로드시키도록 함
- props
lazy
: lazy-loading 적용여부threshold
: 얼마만큼 걸쳐야 이미지 로딩을 시작할 것인지 (0.5면 절반 보일 때 이미지 로딩 시작)placeholder
: 이미지 없을 때 대체할 이미지 주소
4. Spinner 컴포넌트 with Storybook
loading 값에 따라, Spinner 아이콘을 출력
- props
- size, color, loading
5. Toggle 컴포넌트 with Storybook
switch와 같은 컴포넌트로 true/false를 기본 상태로 가지는 컴포넌트
- input의 checked 속성을 통해, 하위 css 속성을 변화시킬 수 있는 트릭을 사용
- props
on
: 초기 on/off 값disabled
: 사용가능한 toggle 여부- disabled 시 css의 opacity 낮추고, cursor: not-allowed 설정
onChange
: