0

How do you do this in stateless functional components? I tried this but it doesn't work: ComponentName.componentDidMount = () => document.title = "Who's Marco?" Where the ComponentName is something like this:

export const Life = ({sayHello="Ciao"}) => (

)
ocram
  • 1,384
  • 6
  • 20
  • 36
  • 4
    If you want to use React lifecycle methods (e.g. `componentDidMount`) then your component is no longer Stateless and thus is now Stateful. – Dan May 24 '17 at 10:39
  • oh that's a shame but thanks – ocram May 24 '17 at 10:40
  • I changed it to a class but `ComponentName.componentDidMount = () => document.title = "Who's Marco?"` still doesn't work... – ocram May 24 '17 at 12:21
  • You would need something like this: https://www.webpackbin.com/bins/-KkuSqHpVeJ2UVGOh6TX - This will render the document title as `Ciao!` – Dan May 24 '17 at 12:40
  • Does this answer your question? [How do you set the document title in React?](https://stackoverflow.com/questions/46160461/how-do-you-set-the-document-title-in-react) – Jordan Daniels Dec 20 '19 at 22:59

2 Answers2

3

With a functional component, you can use useEffect.

For example,

useEffect(() => {
  document.title = "Who's Marco?"
}, []);

Adding the empty array in useEffect calls the function only once, just like a componentDidMount life cycle method.

Jordan Daniels
  • 4,896
  • 1
  • 19
  • 29
0

You could use something like react-helmet to change the title in the render method, which should keep your component stateless. This does mean adding a dependency to your project though, and may be overkill for your needs.

const HelloWorld = ({name}) => (
  <div>
    {`Hi ${name}`}
    <Helmet>
        <title>Who's Marco?</title>
    <Helmet>
  </div>
);
MunkyJunky
  • 379
  • 4
  • 14
  • I changed it to a class but `ComponentName.componentDidMount = () => document.title = "Who's Marco?"` still doesn't work... – ocram May 24 '17 at 12:20