Add Favicon to React Applications

  1. Add Favicon to React Applications Using react-favicon
  2. Add Favicon to React Applications Using html-webpack-plugin

Module bundlers like Webpack make it possible to build modern applications by combining important front-end assets such as images, fonts, and stylesheets into one output file.

Favicon is one of those visual assets used in many web applications. It is the icon that appears next to the title of a web page in the browser tab.

It can be useful to add branding to your website and distinguish it from competitors. This article will explore how to add favicons to React applications using Webpack.

Add Favicon to React Applications Using react-favicon

This is probably the easiest way to add the favicon to React apps. To update the favicon of your app, you only have to import a Favicon component and set its url attribute equal to the URL of the image you want to use as a favicon.

Example:

import Favicon from "react-favicon";

export default function App() {
  return (
    <div className="App">
      <Favicon url="https://pbs.twimg.com/profile_images/1455185376876826625/s1AjSxph_400x400.jpg"></Favicon>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Our entire React application consists of one App component in this example. We import the Favicon component from the 'react-favicon' package and include it in the main <div> container.

We can include the component anywhere in our component tree, and it will still update the favicon of your website. Then we set the url attribute to an image (which is a Google logo).

If you open this live demo, you’ll see that the favicon of your app is indeed set to the Google logo.

Add Favicon to React Applications Using html-webpack-plugin

Alternatively, you can install the html-webpack-plugin tool to contain your Webpack module bundles in your website’s ` section and use them as needed.

Once installed, you will have to edit the webpack.config.js. Find the plugins property, which is usually an array.

Add the following value to that array:

new HtmlWebpackPlugin({
    favicon: "./src/favicon.gif"
})

For this solution to work, you will need to add the favicon.gif file to your React app project’s src folder.

This will make the favicon file available in the build folder and make it available in the final output of your page.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.