[6주차] React 심화 1 - 실습

minLuna·2023년 4월 8일
0

엘리스 AI트랙 7기

목록 보기
40/62

본 자료는 생활코딩 이고잉 코치님과 Elice 플랫폼의 자료를 사용하여 정리하였습니다.

다른 컴포넌트에 함수 넘겨주기

  • 다른 컴포넌트가 Props.함수 형태로 받는다면 <태그 함수명={함수}> 형태로 전달

Route 태그

  • import Route from 'react-router-dom'입력
  • <Route path="경로" element={<Main /> }> 은 컴포넌트이다.

query string 전달하기

전달

const history = useHistory();
history.push({
  pathname: "/detail",
  search: `?email=${email&password=${password}`,
});

수신

const location = useLocation();
const searchParams = new URLSearchParams(location.search);
const email = searchParams.get("email");
const password = searchParams.get("password");

useReducer 사용하기

초기값 설정

const initialState = {
  message: "hi"
}

reducer 생성

const reducer = (state, action) => {
  switch(action.type) {
    case 'type1':
      return { ... } # 초기값을 사용하려면 state. 형태로 사용
    case 'type2':
      return { ... }
    default:
      throw new Error()
  }
}

useReducer 선언

const [state, dispatch] = useReducer(reducer, initialState)

return (
  <div>
    <button onClick={() => {
      dispatch({ type: "type1", payload: "전달하려는 값" })
    }}
    </button>
  </div>
)

dispatch 사용

dispatch({ type: "type1", payload:" 전달하려는 값" }); # payload는 생략가능하다.

useContext 사용하기

  • props 대신 사용하여 context 범위에 있는 컴포넌트는 모든 값을 공유한다.

선언하기

const MyContext = createContext();

값 넘겨주기

return (
  <MyContext.Provider value={공유할 값}>
    <Welcome /> # 컴포넌트
  </MyContext.Provider>
)

값 넘겨받기

const {공유받은 값} = useContext(MyContext);

useRef 사용하기

  • DOM을 선택하는 용도로 사용가능

선언하기

const inputRef = useRef();

값 꺼내오기

<input type="text" data-testid="input" ref={inputRef} />
console.log(inputRef.current.value)
profile
열심히

0개의 댓글