0
votes

I need to add dynamic value to the <title></title> of the page. I am using Head component provided by next/head for that.

The title needs to change on some user action (hence cannot be placed in the _app.js or _document.js).

However, if I place this code: <Head><title>Page title</title></Head> anywhere other that _app.js or _document.js, the appears in the <body> tag of the page, which is not desired.

enter image description here

// modules/about_us/index.js

import Head from 'next/head'

export default class AboutUs extends Component {
  state = {
    title: 'About you'
  }
  someEvent1(){
    this.setState({title : 'About team'})
  }
  someEvent2(){
    this.setState({title : 'About company'})
  }
  render(){
    return (
      <div>
        <Head>
          <title>{this.state.title}</title>
        </Head>
        <div>This is one of the module used to display the page.</div>
        <button onClick={this.someEvent1}>About team</button>
        <button onClick={this.someEvent2}>About company</button>
      </div>
    )
  }
}
2
Did you ever find the answer?edward-hong
Running into this as wellSteven Baughman

2 Answers

-1
votes

I would recommend using pure javascript rather than attempting to adjust it through jsx / markup.

document.title = 'My New Title';

https://developer.mozilla.org/en-US/docs/Web/API/Document/title

-1
votes

You could use the react-helmet lib for that

From the readme:

import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
                <link rel="canonical" href="http://example.com" />
            </Helmet>
            ...
        </div>
    );
  }
};