Hook - useClick

원종서·2021년 8월 25일
0

hook

목록 보기
4/11

useRef

우리의 컴포넌트의 특정 부분을 선택할 수 있는 방법
document.getElementById() 와 같음

import React, { useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";


const useClick = (onClick) => {
  const element = useRef();
  const componentWillUnMount = () => {
    if (element.current) {
      element.current.removeEventListener("click", onClick);
    }
  };
  useEffect(() => {
    // useEffet excutes when being mounted and updated
    if (element.current) {
      element.current.addEventListener("click", onClick);
    }
    //  function useEffet excutes when being unmounted
    return componentWillUnMount;
  }, []);

  if (typeof onClick !== "function") {
    return;
  }
  return element;
};
const App = () => {
  const hi = () => console.log("hello~");

  const title = useClick(hi);
  return (
    <div className="App">
      <h1 ref={title}>gg</h1>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

0개의 댓글