TIL.50 Hooks-custom hooks

Haiin·2021년 1월 29일
0
post-thumbnail

출저



useConfirm

사용자가 이벤트를 일으켰을때 (보통 클릭 이벤트) 다시 한번 확인하는 창을 띄워주고 확인을 했을때 처음에 시도했던 이벤트를 실행시키는 hook이다.

사용자가 삭제버튼 클릭 -> "정말 삭제할꺼니?" 라는 메세지 창 -> 메세지 창에서 사용자가 "응" 버튼 누르기 -> 메세지 창이 꺼지고 삭제가 실행

import React from "react";

const useConfirm = (message = "", onConfirm, onCancel) => {
  if (typeof callback !== "function") {
    return "Take a function!";
  }
  // 두 번째 인자로 들어온 함수가 "함수형"인지 확인
  const confirmAction = () => {
    if (window.confirm(message)) {
      onConfirm();
    } else {
      onCancel()
    }
  };
  // 첫 번째 인자와 두 번째 인자를 사용하여 "확인 메세지창"을 띄움
  return confirmAction;
  // 결국 useConfirm 이라는 hook 은 값으로 confirmAction()을 리턴한다.
};

const App = () => {
  // 자 이제 hook 을 만들었으니 한번 사용해 볼까
  // 두 번째 인자에 들어갈 콜백함수를 먼저 만들어 놓고, confirmDelete라는 이름으로 hook을 불러본다.
  const deleteWorld = () => console.log("Deleting...");
  const abort = () => console.log("Aborted")
  const confirmDelete = useConfirm("Are you sure?", deleteWorld, abort);
  return (
    <div className="App">
      <h1>Hello</h1>
      <button onClick={confirmDelete}>Delete the world</button>
      // (세상을 지워버리시겠습니까..?)
    </div>
  );
};

export default App;

참고

window.confirm, alert, prompt 모두 브라우저에서 모달처럼 새창을 띄워주는 기능



useFadeIn

선택한 태그를 애니메이션을 준 것 처럼 나타나게 하고자 할때 useFadeIn 이라는 hook 을 만들어 놓으면 인자에 따라 나타나는 시간이나 방법을 다르게 표현할 수 있다.

기본세팅

import React, { useEffect, useRef } from "react";

const useFadeIn = () => {
  const element = useRef();
  return element;
};

// 1. "useFadeIn"이라는 custom hook을 만든다.
// 2. 사용하고자 하는 view에 만들어 놓은 hook 을 쓰기위해 변수에 할당해 준다.

const App = () => {
  const el = useFadeIn()
  return (
    <div className="App">
      <h1 ref={el}>Hello</h1>
    </div>
  );
};

export default App;

FadeIn 추가

import React, { useEffect, useRef } from "react";

const useFadeIn = (duration = 1, delay = 0) => {
  if (typeof duration !== "number" || typeof delay !== "number") {
    return;
  }

  const element = useRef();
  
  useEffect(() => {
    if (element.current) {
      const { current } = element;
      current.style.transition = `opacity ${duration}s ease-in-out ${delay}s`;
      current.style.opacity = 1;
    }
  }, []);
  return { ref: element, style: { opacity: 0 } };
};
// useEffect 를 이용하여 실행시킬 fadeIn 을 설정해준다.
// useRef를 사용하면 current를 통해 선택한 태그의 프로퍼티에 접근가능하며, 객체형태로 설정도 가능하다.
// return 값에도 객체로 할당하여 아래와 같이 변수에 할당하면 {...}(spread operator)형태로 받아서 매번 렌더링을 통해 객체를 전달할 수 있다.
const App = () => {
  const fadeInH1 = useFadeIn(3, 2);
  const fadeInP = useFadeIn(1, 5);
  return (
    <div className="App">
      <h1 {...fadeInH1}>Hello</h1>
      <p {...fadeInP}>hahahaahahahahah</p>
    </div>
  );
};

export default App;


0개의 댓글