[React JS] #Hooks 3

7504 단어 react jsreact js

# USEEFFECT

6. useScroll

const useScroll = () => {
  const [state, setState] = useState({
    x: 0,
    y: 0
  });
  const onscroll = () => {
    setState({ y: window.scrollY, x: window.scrollX });
  };
  useEffect(() => {
    window.addEventListener("scroll", onscroll);
    return () => window.removeEventListener("scroll", onscroll);
  }, []);
  return state;
};

const App = () => {
  const { y } = useScroll();
  return (
    <div style={{ height: "1000vh" }}>
      <h1 style={{ position: "fixed", color: y > 100 ? "red" : "blue" }}>
        Hello!
      </h1>
    </div>
  );
};

7. useFullscreen

const useFullscreen = (callback) => {
  const element = useRef();
  const triggerFull = () => {
    if (element.current) {
      element.current.requestFullscreen();
      if (callback && typeof callback === "function") {
        callback(true);
      }
    }
  };
  const exitFull = () => {
    document.exitFullscreen();
    if (callback && typeof callback === "function") {
      callback(false);
    }
  };
  return { element, triggerFull, exitFull };
};

const App = () => {
  const onFulls = (isFull) => {
    console.log(isFull ? "We are full" : "We are small");
  };
  const { element, triggerFull, exitFull } = useFullscreen(onFulls);
  return (
    <div style={{ height: "1000vh" }}>
      <div ref={element}>
        <img src="http://image.newsis.com/2021/05/03/NISI20210503_0017412357_web.jpg" />
        <button onClick={triggerFull}>Make fullscreen</button>
        <button onClick={exitFull}>exit fullscreen</button>
      </div>
    </div>
  );
};

8. useNotification

useAxios.js

const useAxios = (opts, axiosInstance = defaultAxios) => {
  const [state, setState] = useState({
    loading: true,
    error: null,
    data: null
  });
  const [trigger, setTrigger] = useState(0);
  if (!opts.url) {
    return;
  }
  const refetch = () => {
    setState({
      ...state,
      loading: true
    });
    setTrigger(Date.now());
  };
  useEffect(() => {
    axiosInstance(opts)
      .then((data) => {
        setState({
          ...state,
          loading: false,
          data
        });
      })
      .catch((error) => {
        setState({ ...state, loading: false, error });
      });
  }, [trigger]);
  return { ...state, refetch };
};

Index.js

const App = () => {
  const { loading, data, refetch } = useAxios({
    url: "https://yts.am/api/v2/list_movies.json"
  });
  return (
    <div>
      <h1>{data && data.status}</h1>
      <h1>{loading && "Loading"}</h1>
      <button onClick={refetch}>refetch</button>
    </div>
  );
};

좋은 웹페이지 즐겨찾기