ios, web, thoughts & notes (rss)

dreamscape by isak solheim

13 jan 2022 ~

React Image onLoad

In React, you can track the state of whether and image has loaded or not by passing the onLoad prop to an <img /> element.

For my personal website, I have written the following Header.tsx component:

const Header = () => {
  const [loaded, setLoaded] = useState(false);

  const handleOnLoad = () => setLoaded(true);

  return (
      {!loaded && <EmptyContributionGraph />}
        alt="Github contribution graph"
      <TextLink url="/" text="" />

I use the useState hook to add React state and keep track of the loaded value. Once the <img /> has loaded, the function handleOnLoad runs, which flips the loaded state from false to true. The temporary image <EmptyContributionGraph /> will not disappear.

This is what the final component looks like:

Example of onLoad