본문 바로가기
스파르타코딩클럽/내일배움캠프

[TIL] 내일배움캠프 React 과정 2023.01.18

by heereal 2023. 1. 18.

Today I Learned

  • Typescript로 React TO-DO-LIST 리팩토링하기

 


Recoil 공부

공식 문서 https://recoiljs.org/ko/docs/introduction/getting-started/

참고 영상 https://www.youtube.com/watch?v=t934FOlOMoM

 

 

typescript로 react project 만들기

index.tsx 에러

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);

as HTMLElement라고 타입을 지정해줘야 한다.

 

 

typescript에서 styled-components 사용하기

npm i --save-dev @types/styled-components

하라는 대로 설치하니까 에러가 사라졌다!

 

Router.ts

.ts가 아니라 .tsx로 변경해야 한다.

 

 

jsx->tsx 에러 하나씩 해결하기

useSelector

 

export type RootState = ReturnType<typeof store.getState>
useSelector((state: RootState) => state.todos);

RootState를 사용하면 state의 타입을 알아서 지정해준다고 한다. indes.ts에 RootState를 export하고 useSelctor를 사용할 때 import해서 state의 타입을 RootState로 지정한다.

 

 

객체에 type 지정

todos.find((list: TodosType) => list.id === param.id);

다양한 방법이 있겠지만 나는 interface를 이용했다.

 

 

event의 type은?

input에 값을 입력했을 때 e.target.value로 그 입력한 내용을 가져오는 함수인데 과연 여기서 e의 type은 무엇일까?

input 태그의 onChange에 마우스를 올려보면 해당 type을 알 수 있다.

e: React.ChangeEvent<HTMLInputElement>

참고 https://velog.io/@ahn0min/TypeSCript-event-의-type-은-무엇일까

 

 

styled-components props 받을 때

const Btn = styled.button<{backgroundColor: string}>`
    background-color: ${(props) => props.backgroundColor};
`

참고 https://velog.io/@altjsvnf/TS-TypeScript에서-Styled-component-사용하기

 

 

useRef 사용하기 (current.focus)

const titleRef = useRef<HTMLInputElement>(null);
if ( !title && !content && titleRef.current ) {
      e.preventDefault();
      titleRef.current.focus()
      alert('제목과 내용을 모두 입력해주세요.')
}

if문 조건에 ref.current인 경우를 추가해야 한다.

 

참고

https://curryyou.tistory.com/488

https://velog.io/@rkio/Typescript-useRef와-Typescript를-같이-사용하는-경우

https://driip.me/7126d5d5-1937-44a8-98ed-f9065a7c35b5

 

 

uuid 설치하기

npm i --save-dev @types/uuid

 

button 태그 onClick

const addHandler = (e: React.FormEvent<HTMLFormElement>) => {
}

input에 제목과 내용을 입력하고 [추가하기] 버튼을 클릭하면 정보가 state에 저장되는 부분인데 onClick이 자꾸 에러가 떠서 button 태그가 아니라 form 태그에 onSubmit을 사용하는 방식으로 수정했더니 해결되었다.

 

 

컴포넌트를 통해 props를 받아올 때

// props 보내는 부분
<TodoList isDone={false} />

// porps 받아 오는 부분
interface IsDone { isDone: boolean }
function TodoList ({isDone}: IsDone) {

}

 


Programmers 문제 풀기

삼각형의 완성 조건

나의 풀이

function solution(sides) {
    sides.sort((a,b)=>b-a)
    if (sides[0] < sides[1] + sides[2]) return 1
    else return 2
}

어제 배운 sort() 메서드 바로 사용하기!

 

다른 사람의 풀이

function solution(sides) {
    sides = sides.sort((a,b) => a-b)
    return sides[0]+sides[1] > sides[2] ? 1 : 2;
}

return 부분을 삼항연산자를 이용해서 더욱 깔끔하게 작성할 수 있다.

 

 

짝수는 싫어요

function solution(n) {
    let array = [];
    for (i = 1; i <= n; i+=2) {
        array.push(i)
    }
    return array;
}

 

중앙값 구하기

나의 풀이

function solution(array) {
    array.sort((a,b)=>a-b)
    let index = Math.floor(array.length/2)
    return array[index];
}

 

다른 사람의 풀이

function solution(array) {
  return array.sort((a, b) => a - b)[Math.floor(array.length / 2)];
}

나랑 동일한 풀이지만 코드를 한 줄로 간결하게 정리할 수 있었다.

 

배열의 유사도

function solution(s1, s2) {
    return s1.filter((x) => s2.includes(x)).length
}

처음엔 2중 for문을 생각했다가 배열 안에 있는 요소를 찾는 메서드는 없을까 검색해서 찾아냈다. 내가 작성한 답변이 두 배열의 교집합을 찾아주는 것이라고 생각하면 된다. s1 배열을 filter를 돌리는데 s2 배열에 x라는 동일한 요소가 있을 때만 배열에 넣어주는 것이다.

 

참고 https://soft91.tistory.com/84

 


회고

오전에는 타입스크립트 공부하기 싫어서 프로그래머스 문제를 조금 풀고 오후에는 갑자기 타입스크립트 타임어택 과제가 떠서 정신없이 시간을 보냈다. 과제는 기존에 만들었던 react-redux 투두리스트를 타입스크립트를 이용해서 리팩토링하는 것이었는데 나는 아예 타입스크립트를 적용한 리액트 프로젝트를 새로 만들어서 기존의 폴더를 가져온 후에 js->ts로 바꾸는 식으로 리팩토링을 했다. 사실 너무 갑자기 주어진 과제에 당황스럽긴 하지만 직접 해 보면서 배우는 게 빨리 실력을 늘릴 수 있는 방법인 거 같긴 하다.

 

 

댓글