skip to Main Content

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>

2

Answers


  1. How about directly changing the document object after acquiring the data from the API?

    const data = await fetchMyData();
    
    document.title = data.brandName;
    
    const faviconElement = document.querySelector("link[rel='icon']");
    if (faviconElement) {
      faviconElement.href = data.profileImage;
    }
    
    Login or Signup to reply.
  2. First you need to fetch some data

    import React, { useEffect, useState } from 'react';
    function App() {
      const [brandName, setBrandName] = useState('');
      const [profileImage, setProfileImage] = useState('');
    
      useEffect(() => {
        const fetchData = async () => {
          try {
            const response = await fetch('REQUESTED_URL');
            const data = await response.json();
            setBrandName(data.brandName);
            setProfileImage(data.profileImage);
          } catch (error) {
            console.error('Error fetching brand data:', error);
          }
        };
    
        fetchData();
      }, []);
    
      useEffect(() => {
        // Set document title
        if (brandName) {
          document.title = brandName;
        }
    
        // Set favicon
        if (profileImage) {
          const favicon = document.getElementById('favicon');
          favicon.href = profileImage;
        }
      }, [brandName, profileImage]);
    
      return (
        <div className="App">
          <h1>Welcome to {brandName}</h1>
        </div>
      );
    }
    
    export default App;
    

    Then update your index.html

    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <link id="favicon" rel="icon" type="image/svg+xml" href="default-icon.svg" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Default Title</title>
      </head>
      <body>
        <div id="root"></div>
        <script type="module" src="/src/main.jsx"></script>
      </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search