reactjsfavicon

How to Dynamically Update Document Title and Favicon in a React Application Using Data from an API


I am building a React application and I need to dynamically update the document title and favicon based on data fetched from an API. Specifically, I want to use the brandName field from my API response to set the document title and favicon.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" **href={profileImage}**/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>**{brandName}**</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

Solution

  • Make use of 'useState' and 'useEffect'

    you need to make a function that will fetch and set the value of the icon and brand name from the API. After the data has been fetched, you can use javascript to update the said title and favicon dynamically.

    function App() {
      const [brandName, setBrandName] = useState('');
      const [profileImage, setProfileImage] = useState('');
    
    //Data Fetching
      useEffect(() => {
        async function fetchData() {
          try {
            const response = await fetch('YOUR_API_ENDPOINT');
            const data = await response.json();
            
            //Set the value of the brandName and favicon/profile
            setBrandName(data.brandName);
            setProfileImage(data.profileImage);
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        }
    
        fetchData();
      }, []);
    
    //Update the brandName dynamically
      useEffect(() => {
        if (brandName) {
          document.title = brandName;
        }
      }, [brandName]);
    
    //Update the profileImage / favicon dynamically
      useEffect(() => {
        if (profileImage) {
          const link = document.querySelector("link[rel*='icon']") || document.createElement('link');
          link.type = 'image/svg+xml';
          link.rel = 'icon';
          link.href = profileImage;
          document.getElementsByTagName('head')[0].appendChild(link);
        }
      }, [profileImage]);
    
      return (
        <div>
          <h1>Welcome to {brandName}</h1>
        </div>
      );
    }
    
    export default App;