Changing favicon according to OS theme
Most operating systems now offer light and dark modes. Sometimes the default favicon does not work well in dark mode due to the lack of contrast. This recipe explains how to add a favicon variant for dark mode into the project.
Walk-through
1. Generate the dark variant favicon files
It is recommended the use of the generator RealFaviconGenerator. Follow these steps:
Select an image (PNG, JPG or SVG). Your image should be 260x260 or more for optimal results.
Tweak the options just for the "Favicon for Desktop Browsers and Google Result Pages" section. Please include a UI Designer in this process for optimal results.
❗️ At the bottom, on the "Favicon Generator Options" section go to the "Compression" tab and select "Very high quality, very low compression factor".
Press the button to generate the favicon package. Once the package is ready, download it to your computer.
2. Add the files to the project
Extract the package you downloaded in the previous step and extract it to a temporary folder.
Rename
favicon-32x32.png
,favicon-16x16.png
andfavicon.ico
tofavicon-dark-32x32.png
,favicon-dark-16x16.png
andfavicon-dark.ico
respectively.Copy these same files to the
public/favicons
folder.
react-use-system-theme
3. Install useSystemTheme
hook in the App.js
4. Use the We will be using react-use-system-theme to get the current OS theme and conditionally render both favicon variants:
Please note that some of the head tags were duplicated and are being rendered conditionally based on the system theme. Moreover, we have used the same version (?v=xxxxx
) for both variants.