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 isak.me, I have written the following Header.tsx component:

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

  const handleOnLoad = () => setLoaded(true)

  return (
    <header>
      {!loaded && <EmptyContributionGraph />}
      <img
        src="https://ghchart.rshah.org/isaksolheim"
        className="contribution-graph"
        alt="Github contribution graph"
        onLoad={handleOnLoad}
      />
      <TextLink url="/" text="isak.me" />
    </header>
  )
}

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

Reply via emailBuy me a coffee

Join the newsletter

Every two weeks, I send an email about things that interest me, things I have built and things I have learned.

Previous issues