Random Access Components

use-os

Hook to detect the current operating system

Demo

Current OS

unknown

Open on other operating systems to see different values

"use client";
import { useOs } from "@/hooks/use-os";

const UseOsDemo: React.FC = () => {

    const os = useOs();
    return ( 
      <div className="text-center space-y-4">
        <div className="text-sm text-muted-foreground">
          Current OS
        </div>
        <p className="text-lg font-semibold text-foreground">
          {os}
        </p>
        <p className="text-sm text-muted-foreground mt-8">
          Open on other operating systems to see different values
        </p>
      </div>
    );
}
 
export { UseOsDemo };

Installation

Copy and paste the following code into your project.

use-os.ts
"use client";
import { useState, useEffect } from "react";

const getOs = () => {
  if (typeof window === "undefined") {
    return "unknown";
  }

  const userAgent = window.navigator.userAgent;

  if (/Windows|Win32|Win64|WinCE/.test(userAgent)) {
    return "windows";
  } else if (/Mac OS X|Macintosh/.test(userAgent)) {
    return "macos";
  } else if (/Linux/.test(userAgent)) {
    return "linux";
  } else if (/iPhone|iPad|iPod/.test(userAgent)) {
    return "ios";
  } else if (/Android/.test(userAgent)) {
    return "android";
  }

  return "unknown";
};

type Os = "macos" | "windows" | "ios" | "android" | "linux" | "unknown";

export const useOs = () => {
  const [os, setOs] = useState<Os>("unknown");

  useEffect(() => {
    setOs(getOs());
  }, []);

  return os;
};

Usage

import { useOs } from "@/hooks/use-os";
const os = useOs();

On this page