React JS 마스터클래스

JIHYE·2022년 12월 7일
0
post-thumbnail

1. STYLED COMPONENTS

1.1 설치

  • npm i styled-components

1.2 사용법

  • styled.{element}``;
  • &: 가상 선택자로 자기 자신을 뜻함
import styled, {keyframes} from 'styled-components';

const Wrapper = styled.div`
  display:flex;
  height:100vh;
  width:100vw;
  justify-content:center;
  align-items:center;
  background-color:${props => props.theme.backgroundColor};
`;

const Btn = styled.button`
  color:white;
  background-color: tomato;
  border:0;
  border-radius:15px;
`;

const rotateAnimation = keyframes` // Animation
  0% {
    transform:rotate(0deg);
    border-radius:0px;
  }
  50% {
    border-radius:40px;
  }
  100% {
    transform:rotate(360deg);
    border-radius:0px;
  }
`;
`;

const Box = styled.div`
  background-color:${props => props.bgColor};
  width:100px;
  height:100px;
  display:flex;
  justify-content:center;
  align-items:center;
  animation:${rotateAnimation} 1s linear infinite;
  ${Emoji}:hover {
      font-size:98px;
  }
`;

/* Box의 스타일을 상속받고 다른 스타일도 추가 적용 */
const Circle = styled(Box)`
  border-radius:50%;
`;

/* 여러번 사용하는 경우 styled-component를 사용하여 속성을 한번만 설정해줌으로써 중복을 제거할 수 있음 */
const Input = styled.input.attrs({required:true})`
  background-color:${props => props.theme.textColor};
`;

const Text = styled.h1`
  color:${props => props.theme.textColor};
`;

function App() {
  return (
    <Wrapper as="header"> // as를 사용함으로써 div가 아닌 header로 동작하게 함
      <Btn>Log in</Btn>
      <Btn as="a" href="/">Log in</Btn>
      <Box bgColor="tomato">
        <Emoji>😊</Emoji>
      </Box>
      <Circle bgColor="orange"/>
      <Input/> // styled-component를 사용해 required 설정됨
      <Input/> // styled-component를 사용해 required 설정됨
      <Emoji>🌠</Emoji>
      <Text>Hello</Text>
    </Wrapper>
  );
}

2. TYPESCRIPT

2.1 설치법

2.1.1 새로운 프로젝트 생성

  • npx create-react-app 프로젝트명 --template typescript
  • yarn create react-app 프로젝트명 --template typescript

2.1.2 기존 프로젝트에 설치

  • npm install --save typescript @types/node @types/react @types/react-dom @types/jest
  • yarn add typescript @types/node @types/react @types/react-dom @types/jest

2.1.3 기타

  • TypeScript에서 라이브러리가 동작하도록 하기 위해서 type definition을 설치해야함
  • npm i --save-dev @types/styled-component
  • npm i styled-components
  • ReactDOM.createRoot(document.getElementById('root')) -> ReactDOM.createRoot(document.getElementById('root') as HTMLElement)변경(오류가 발생하면)
  • .ts.tsx의 차이 : .ts는 typescript이며 .tsx는 typescript + react 문법을 사용
const value = event.currentTarget.value;
const tagName = event.currentTarget.tagName;
const width = event.currentTarget.width;
const id = event.currentTarget.id;

const {
currentTarget: {value, tagName, width, id} // event안 curentTarget안에 value의 값을 기존 이름 그대로 value, tagName, width, id 라는 변수를 만듦
} = event;

2.2 사용법

2.2.1 예시1

const plus = (a:number, b:number) => a + b;
plus(1,2) // 정상
plus("a", 2) // 오류

2.2.2 예시2

interface ContainerProps {
    bgColor : string;
    borderColor: string;
}

const Container = styled.div<ContainerProps>`
    width:200px;
    height:200px;
    background-color: ${props => props.bgColor};
    border-radius:100px;
    border:5px solid ${props => props.borderColor}
`;

interface CircleProps {
    bgColor : string;
    borderColor?: string;
    text?: string;
}

function Circle({bgColor, borderColor, text = "default text"}:CircleProps){
    const [value, setValue] = useState<number|string>(0);
    setValue(2);
    setValue("hello");
    // setValue(true); 에러
    return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}> {text}</Container> // borderColor 가 없으면 bgColor로 사용
}

interface playerShape {
    name:string;
    age:number;
}

const sayHello = (playerObj:playerShape) => `Hello ${playerObj.name} you are ${playerObj.age} years old.`

sayHello({name:"hi", age:2})
sayHello({name:"gildong", age:100})

2.2.3 예시3

const [value, setValue] = useState("");
  const onChange = (e:React.FormEvent<HTMLInputElement>) => {
    const {currentTarget: {value}} = e;
    setValue(value);
  };
  const onSubmit = (e:React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    console.log("hello", value);
  }

  return (
    <div>
      <form onSubmit={onSubmit}>
        <input type="text" placeholder='username' value={value} onChange={onChange}/>
        <button>Log in</button>
      </form>
    </div>  
  );

3. CRYPTO TRACKER

3.1 설치

3.1.1 REACT ROUTER 설치

  • npm i react-router-dom@5.3.0

3.1.2 REACT QUERY 설치

3.2 기타 참고사항

  • react-router-dom@5.3.0 사용 시 URL은 변하는데 렌더링이 안되는 문제 => <React.StrictMode> 제거
// (함수)(); 를 사용하면 해당 로직을 바로 호출할 수 있음 
(async() => {
        fetch("https://api.coinpaprika.com/v1/coins");
      })();

4. STATE MANAGEMENT

4.1 Recoil

  • Recoil는 React를 위한 상태 관리 라이브러리

4.1.1 Recoil 설치

  • npm install recoil
  • yarn add recoil

4.1.2 Atom

  • selector은 atom을 보고있으며 get 함수가 필요
  • atom의 상태를 가져와서 filter 하여 새롭게 반환할 수 있음

4.2 React Forms

4.2.1 React Forms 설치

  • npm install react-hook-form

4.2. React Forms 사용

  • register : Object 반환. 입력 등록, 요소 선택, 유효성 검사 규칙을 React Hook Form에 적용할 수 있음
    • name, onChange, onBlur, ref 값이 들어있음
  • watch : state. 지정된 입력을 감시하고 해당 값을 반환
  • handlerSubmit : 인자 2개 필요. onValid(필수), inValid(선택). 양식 유효성 검사가 성공하면 양식 데이터를 수신
  • formState : 에러 반환.
  • React Forms API

4.3 정규표현식

5. TRELLO CLONE

5.1 react-beautiful-dnd

5.1.1 react-beautiful-dnd 설치

  • npm i react-beautiful-dnd
  • npm i --save-dev @types/react-beautiful-dnd

5.2 React memo

  • 고차 컴포넌트(HOC : Higer Order Component)
  • react memoprop이 바뀌지 않는다면 컴포넌트를 렌더링 하지 않도록 하는 역할
  • 컴포넌트가 동일한 props로 동일한 결과를 렌더링해낸다면, React.memo를 호출하고 결과를 메모이징(Memoizing)하도록 래핑하여 컴포넌트를 렌더링하지 않고 마지막으로 렌더링된 결과를 재사용

5.2.1 React memo 사용법

export default React.memo(DragabbleCard);

5.3 Publishing

  • npm i gh-pages : 결과물을 github pages에 업로드할 수 있게 해주는 패키지
  • npm run build : build 폴더 생성됨
  • 배포방법

gh-pages로 배포 후 새로고침 시 404 에러 발생

5.4 기타

💡5.4.1 참고

const test = {
    "To Do" : ["a", "b"],
    Doing : [ "c", "d", "e"],
    Done : ["f"]
} 
----------------------------------------------------------
{...test, "To Do" : [1, 2, 3]}
----------------------------------------------------------
// 결과
{
    "To Do": [1, 2, 3],
    "Doing": ["c", "d", "e"],
    "Done": ["f"]
}

5.4.2 DragDrop

  • DragDropContext > Droppable : 드롭할 수 있는 영역 > Draggable : 드래그 할 수 있는 영역
  • Droppable : droppableId(필수),
  • Draggable : draggableId(필수), Index(필수: 정렬순서)
  • dragHandlerProps가 있는 걸 선택해야 드래그 가능

5.5 React ref

  • JavaScript를 사용 할 때, 특정 DOM 을 선택해야 하는 상황에 getElementById, querySelector 같은 DOM Selector 함수를 사용해서 DOM 을 선택. 리액트를 사용하는 프로젝트에서도 가끔씩 DOM 을 직접 선택해야 하는 상황이 발생 할 때 ref 라는 것을 사용
function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
  • react 코드를 이용해 HTML 요소를 지정하고, 가져올 수 있는 방법
  • useRef는 .current 프로퍼티로 전달된 인자(initialValue)로 초기화 된 변경 가능한 ref 객체를 반환
  • 반환된 객체는 컴포넌트의 전 life cycle을 통해 유지
  • 일반적인 사용 사례는 자식에게 접근하는 경우

6. ANIMATIONS

6.1 framer-motion

6.2 framer-motion 설치

  • npm install framer-motion

CRACO(Create React App Configuration Override)

  • CRACO(Create React App Configuration Override)는 CRA에 config 설정을 덮어쓰기 위한 패키지
  • CRA에서 eject를 하지 않아도 root 폴더에 craco.config.js를 추가해서 eslint, babel, postcss 등을 쉽게 설정가능
  • 설치 : npm install @craco/craco --save

6.3 framer-motion 사용

6.3.1 variants

  • initial : 초기 상태
  • animate : 변화 원하는 동작, transition 및 transition type 변경
  • variants : stage를 가지고 있고 animation을 좀 더 편리하게 사용할 수 있도록 도와줌.
    • 부모 요소의 initial, animate, exit값과 동일한 이름을 자식에게 상속하므로 이름을 같게 설정했다면 variants 설정만 해준다면 됨

6.3.2 AnimatePresence

  • AnimatePresence를 사용하면 구성 요소가 React 트리에서 제거될 때 애니메이션 효과를 볼 수 있음
  • React에는 다음과 같은 수명 주기 메서드가 없기 때문에 종료 애니메이션을 활성화해야 함
  • 마운트가 해제될 때 구성 요소에 알리고
    작업(예: 애니메이션)이 완료될 때까지 마운트 해제를 연기할 수 있음
  • AnimationPresence 설명

7. NOMFLIX CLONE

7.1 history

  • 라우트로 사용된 컴포넌트에게 match, location 과 함께 전달되는 props 중 하나
  • 이 객체를 통하여, 우리가 컴포넌트 내에 구현하는 메소드에서 라우터에 직접 접근을 할 수 있음

8. GATSBY 101

8.1 Gatsby

  • 리액트 기반의 프레임워크
  • 개츠비로 만든 대부분의 웹사이트는 빌드, 랜더링될 때 이미 데이터를 안에 포함
  • npm start로 실행시키면 http://localhost:9000로 실행되며 인터넷 환경에 의해 화면이 보일수도 있고 안보일수도 있음
  • npm run build -> npm run serve로 실행하면 http://localhost:9000으로 실행되며 나중에 인터넷 환경이 이상해지더라도 화면이 안보이는 경우가 없음
  • 서버를 킨 상태로 새로운 화면을 추가하게 되면 npm start로 실행시킨 화면은 바로 화면을 볼 수 있지만 npm run serve로 실행시킨 화면은 서버를 껐다 켜야 볼 수 있음

8.1.1 Gatsby 설치

  • npm i -g gatsby-cli

8.1.2 Gatsby 프로젝트 생성

  • gatsby new

💡참고

  • 라이브러리? 개발자들이 불러오는 어떤 대상(import). 제어의 흐림이 개발자에게 있음 ex) React
  • 프레임워크? 원하는 기능 구현에 집중하여 개발할 수 있도록 일정한 형태와 필요한 기능을 갖추고 있는 골격. 제어의 흐름이 프레임워크에 있음 ex) Vue, NextJS, Gatsby

8.2 GraphQL

query {
  allPlanets {
    totalCount
    planets {
      name
      population
    }
  }
  allFilms {
    totalCount
    films {
      title
      director
      releaseDate
    }
  }
  
  film(id:"ZmlsbXM6MQ==") {
    title
    producers
    planetConnection {
      planets {
        name
      }
    }
    speciesConnection {
      species {
        name
      }
    }
  }
}
  • useStaticQuery : 정적 쿼리 사용. useStaticQuery는 빌드 시 리액트 훅을 사용하여 Gatsby의 GraphQL 데이터 계층을 쿼리하는 기능을 제공. 이를 통해 React 컴포넌트는 구문 분석, 평가 및 컴포넌트에 삽일될 GraphQL 쿼리를 통해 데이터를 검색 할 수 있음
  • https://www.gatsbyjs.com/plugins

[출처] https://nomadcoders.co/react-masterclass

0개의 댓글