Dynamic favicon using React

Let's assume that you want to add a favicon dynamically depending on the theme colour (dark or light). First, add both favicons to the public folder. In this example, dark.ico and light.ico will change depending on the user's colour scheme.

Modify index.html and add id = 'favicon' to the favicon link:

html
<link rel = 'shortcut icon' href = '%PUBLIC_URL%/favicon.ico' id = 'favicon'>

Add this script in the <head></head>:

html
<script>

    let favicon = document.getElementById('favicon')

    let dark = '%PUBLIC_URL%/dark.ico'
    let light = '%PUBLIC_URL%/light.ico'

    favicon.href = window.matchMedia('(prefers-color-scheme: dark)').matches ? dark : light

    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {

        favicon.href = event.matches ? dark : light

    })

</script>

At first, the script modifies the favicon's href depending on the preferred colour scheme. Then, it adds a listener that changes the favicon if the user changes the theme.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.