by Sai gowtham

How to change the favicon dynamically in React

In this tutorial, we are going to learn about how to dynamically change the favicon in a react app.

Changing the favicon dynamically

This tutorial assumes that you already created a new react app using create-react-app cli.

  1. Open the react app in your favorite code editor.
  2. Navigate to the public folder and open the index.html file, add the id attribute to the following link tag.
<link rel="shortcut icon" id="favicon" href="%PUBLIC_URL%/favicon.ico">

Now, we can access the favicon in our App.js file using document.getElementById() method then we need to update its href property value with a new favicon like this.

App.js
import React from "react";

function getFaviconEl() {
  return document.getElementById("favicon");
}

function App() {

  const handleGoogle = () => {
    const favicon = getFaviconEl(); // Accessing favicon element
    favicon.href = "https://www.google.com/favicon.ico";  };

  const handleYoutube = () => {
    const favicon = getFaviconEl();
    favicon.href = " https://s.ytimg.com/yts/img/favicon-vfl8qSV2F.ico";  };

  return (
    <div className="App">
      <h1>Dynamically changing favicon</h1>
      <button onClick={handleGoogle}>Google</button>      <button onClick={handleYoutube}>YouTube</button>    </div>
  );
}

export default App;

In the above code, we have two buttons which are Google, YouTube, if we click on Google button our favicon is changed to Google's favicon else if we click on YouTube button our favicon is changed to YouTube's favicon.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course