Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rileybathurst/461f5e535e7e74cff7701d85c9628aa9 to your computer and use it in GitHub Desktop.
Save rileybathurst/461f5e535e7e74cff7701d85c9628aa9 to your computer and use it in GitHub Desktop.
Dark mode content in React
import React, { useState, useEffect } from "react";
function DarkText() {
return <h1>hello</>;
}
function LightText() {
return <h1>world</>;
}
export function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
}, [matches, query]);
return matches;
}
function Theme() {
let isSiteDark = useMediaQuery("(prefers-color-scheme: dark)");
return (
<>
{isSiteDark && <DarkText />}
{isSiteDark || <LightText />}
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment