Skip to content

Instantly share code, notes, and snippets.

@samhernandez
Created October 16, 2023 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samhernandez/c2999fde545f4b072afa77ac6763c421 to your computer and use it in GitHub Desktop.
Save samhernandez/c2999fde545f4b072afa77ac6763c421 to your computer and use it in GitHub Desktop.
useDevBgImage() React hook
import { useEffect, useState } from "react";
function useDevBgImage(src) {
const [bgTop, setBgTop] = useState(0);
const [opacity, setOpacity] = useState(100);
useEffect(() => {
document.getElementById('root').style.opacity = String(opacity / 100);
}, [opacity]);
useEffect(() => {
document.body.style.backgroundPositionY = `${bgTop}px`;
}, [bgTop]);
useEffect(() => {
document.body.style.backgroundImage = `url(${src})`;
document.body.style.backgroundPositionX = "50%";
document.body.style.backgroundPositionY = "0px";
document.body.style.backgroundRepeat = "no-repeat";
function onKeyDown(e) {
if (!e.ctrlKey) return;
if (e.shiftKey) {
setBgTop(0);
return;
}
switch(e.key) {
case 'ArrowUp':
setBgTop((prev) => prev - 1);
break;
case 'ArrowDown':
setBgTop((prev) => prev + 1);
break;
case 'ArrowRight':
setOpacity((prev) => Math.min(100, prev + 5));
break;
case 'ArrowLeft':
setOpacity((prev) => Math.max(0, prev - 5));
break;
}
}
document.addEventListener('keydown', onKeyDown);
return () => {
console.log('unmount');
document.removeEventListener('keydown', onKeyDown);
document.body.style.backgroundImage = "";
document.getElementById('root').style.opacity = "1";
}
}, []);
}
export default useDevBgImage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment