DavidHDev / react-haiku

A clean & lightweight collection of React Hooks & Utilities!
https://reacthaiku.dev/
Other
236 stars 48 forks source link

Feature: Added useOrientation custom hook. #66

Closed francoisdillinger closed 1 month ago

francoisdillinger commented 1 month ago

Pull Request Description

Description A hook that tracks the device's orientation and provides updates when it changes.

Acceptance Criteria

Details:

Demo:

Here is a gif demonstrating the hook in action:

useOrientation Hook Demo

Code Changes

Hook Implementation:

import { useState, useEffect } from "react";

type Orientation = {
  orientation: "portrait" | "landscape";
};

export const useOrientation = () => {
  const [orientation, setOrientation] = useState<Orientation>({
    orientation: window.matchMedia("(orientation: portrait)").matches
      ? "portrait"
      : "landscape",
  });

  useEffect(() => {
    const handleOrientationChange = (e: MediaQueryListEvent) => {
      setOrientation({
        orientation: e.matches ? "portrait" : "landscape",
      });
    };

    const portraitMediaQuery = window.matchMedia("(orientation: portrait)");
    portraitMediaQuery.addEventListener("change", handleOrientationChange);

    return () =>
      portraitMediaQuery.removeEventListener("change", handleOrientationChange);
  }, []);

  return orientation;
};

Index File Update:

export { useOrientation } from './hooks/useOrientation';
// ...other exports

Documentation Update: Added a description of the useOrientation hook to the docs/README file.

- [`useOrientation()`](https://reacthaiku.dev/docs/hooks/useOrientation) - Detect when device is in portrait or landscape mode.