Search code examples
javascriptreactjsmeta-tagsremix.run

How to dynamically update meta tags in Remix.run?


I just started to play with Remix.run and got stuck while trying to update the meta title :

import { useState, useEffect } from "react";

export const meta = () => {
  return [
    { title: "The count is: " },  // I want to show the count here
    { name: "description", content: "Count app" },
  ];
};

export default function Index() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const interval = setInterval(() => {
      setCount(count + 1);
    }, 1000);
    return () => {
      clearInterval(interval);
    };
  });
  return (
    <>
      <h1>The current count is : {count}</h1>
    </>
  );
}

How do I show the count in the meta title & keep synchronized the value?


Solution

  • You may update page title with document.title from useEffect itself.

    You may try something like this:

    import {useState, useEffect} from 'react';
    
    export const meta = () => {
      return [
        {title: 'The count is: '}, // I want to show the count here
        {name: 'description', content: 'Count app'},
      ];
    };
    
    export default function Index() {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        const interval = setInterval(() => {
          setCount(count + 1);
          document.title = `The count is: ${count + 1}`;
        }, 1000);
    
        return () => {
          clearInterval(interval);
        };
      });
    
      return (
        <>
          <h1>The current count is : {count}</h1>
        </>
      );
    }
    

    Edit 1:

    You may also try like this:

    // Another Approach
    useEffect(() => {
      document.title = `The count is: ${count + 1}`;
    }, [count]);