<andres-carmona />

TIL #9: ownerDocument.defaultView
First published on
on html, javascript, typescript

Despite considering my self a seasoned programmer and being developing for over 15 years, I’m surprised I didn’t know about the ownerDocument.defaultView property.

I basically returns the window object (or null) associated with a specific DOM node. It could be used to safely attach an event listener to a window object from a component that is rendered outside the main window where the application was initially rendered (think portals).

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  const ref = useRef(null);

  useEffect(() => {
    const win = ref.current?.ownerDocument.defaultView || window;

    const toggle = (e) => {
      if (e.metaKey && e.key === "d") {
        e.preventDefault();
        setTheme((t) => (t === "dark" ? "light" : "dark"));
      }
    };

    win.addEventListener("keydown", toggle);

    return () => win.removeEventListener("keydown", toggle);
  }, []);

  return (
    <div ref={ref} className={theme}>
      {children}
    </div>
  );
}

From the same article, also learned about useId and cache 😛

Reference: https://shud.in/thoughts/build-bulletproof-react-components, great article btw! 💯


My Game development intro
First published on
on gamedev, games, javascript

Since a long time ago I’ve wanted to start developing a game, and now that my 7 years old kid asked for a game as his next birthday I think is a good time to start. I have no problem learning a new language like Python, C# or Rust, but as a web developer I wanted to start by using my main programming language, Javascript.

So, to start learning (and to get my hands dirty), I want to replicate the game made by Drew Conley Build a Multiplayer Game with JavaScript & Firebase.

More coming soon…