Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

<title> problem: A title element received an array with more than 1 element as children#38256

Discussion options

On my website, users can type a search query into a search field. I would like to set the<title> tag dynamically from this input.

My first question is:Does it make a difference (SEO-wise) if I set this title from a value returned fromgetServerSideProps, or by reading it client-side from the URL query directly? The latter approach would look like this:

const ResourcesPage = ({ [...] }: ServerSideProps & ComponentProps) => {    const router = useRouter();    const searchQueryParam = router.query.q?.toString();   [...]    return (        <div>            <Head>                <title>The best {searchQueryParam} learning resources</title>            </Head>

The other approach would look like this:

export const : GetServerSideProps = async ({ query }) => {    const searchQuery = query.q?.toString();[...]return {          props: {              searchQuery: searchQuery,              resultData: response          }      }const ResourcesPage = ({ searchQuery, [...] }: ServerSideProps & ComponentProps) => {    [...]    return (        <div>            <Head>                <title>The best {searchQuery} learning resources</title>            </Head>

And the second part of the question:No matter which approach I use, I'm getting this warning in the console:

Warning: A title element received an array with more than 1 element as children. In browsers title Elements can only have Text Nodes as children. If the children being rendered output more than a single text node in aggregate the browser will display markup and comments as text in the title and hydration will likely fail and fall back to client rendering

which I didn't find any results in Google for whatsoever.

You must be logged in to vote

Hi,

The warning is because when you do:

constHome:NextPage=()=>{constworld="World";return(<div><span>Hello{world} foo</span></div>);};

React renders:

<div><span>Hello<!-- -->World<!-- --> foo</span></div>

That's adiv with aspan child, with 0 children elements, but 5 nodes as children. There's a subtle difference between elements and nodes. Here's a handyvideo.

The 5 nodes are,text,comment,text,comment,text. The same is happening to yourtitle element.

Do this instead:

constHome:NextPage=()=>{constworld="World";constmessage=`Hello${world} foo`;return(<div><span>{message}</span></div>);};

Which outputs:

Replies: 9 comments 21 replies

Comment options

Hi,

The warning is because when you do:

constHome:NextPage=()=>{constworld="World";return(<div><span>Hello{world} foo</span></div>);};

React renders:

<div><span>Hello<!-- -->World<!-- --> foo</span></div>

That's adiv with aspan child, with 0 children elements, but 5 nodes as children. There's a subtle difference between elements and nodes. Here's a handyvideo.

The 5 nodes are,text,comment,text,comment,text. The same is happening to yourtitle element.

Do this instead:

constHome:NextPage=()=>{constworld="World";constmessage=`Hello${world} foo`;return(<div><span>{message}</span></div>);};

Which outputs:

<div><span>Hello World foo</span></div>

Now thespan has only one,text, child node.

SEO Merits

Well... in either case the bot/crawler, or whatever SEO entity, has to be arrive with the query in the URL already. Since you are usingGSSP, in both cases (right?), for any first request the entire HTML string will be generated server side, so the bot/crawler should parse a correct title.

If you visit the site, with query in the URL, and then right click to "View Page Source", do you see the correct title there? If so, then you are good.

Edit

This answer has gotten a lot of feedback! I've also answered to it in a few other places but I think this one is a good complement:

The key take-away from it:

  • This is part of react-dom's to string rendering.
  • Of course, you can trigger this with any Reactmeta framework:

For example in acodesandbox:

import"./styles.css";import{renderToString}from"react-dom/server";constFooter=()=>{return(<footer><p>{`Copyright ©${newDate().getFullYear()} Sample Company`}</p></footer>);};// const Footer = () => {//   return (//     <footer>//       <p>Copyright © {new Date().getFullYear()} Sample Company</p>//     </footer>//   );// };functionApp(){return(<><divclassName="App"><h1>Hello CodeSandbox</h1><h2>Start editing to see some magic happen!</h2></div><Footer/></>);}console.log(renderToString(<App/>));// log to the console to see what `renderToString` outputs
You must be logged in to vote
13 replies
@cdx111
Comment options

Thank you! Help me that solved it

@1mehdifaraji
Comment options

Thanks for the explanation . worked 100% .

@zohaibasghar
Comment options

yes that's a good approach
thanks for helping buddy

@pajarrahmansyah
Comment options

Very clear! so helpful

@Asylcreek
Comment options

Real clear, thank you kindly

Answer selected byflorianwalther-private
Comment options

I tried the answer here and I seem to still have the error:

Warning: A title element received an array with more than 1 element as children. In browsers title Elements can only have Text Nodes as children. If the children being rendered output more than a single text node in aggregate the browser will display markup and comments as text in the title and hydration will likely fail and fall back to client rendering

I did not have such an error till after I upgraded to Next.JS v12.2.0. So not sure if it's something to do with the version upgrade.

You must be logged in to vote
6 replies
@icyJoseph
Comment options

This is another way to trigger this issue:

<Head><title>{"hello"}</title></Head>

Notice the blank space after"} - subtle.

@discoverlance-com
Comment options

This is another way to trigger this issue:

<Head><title>{"hello"}</title></Head>

Notice the blank space after"} - subtle.

Ok I just checked my head and Yes it had the issue you described here

<Head>    <title>{`${title} - Website`} </title></Head>

I removed the extra space after the} and it works now. Thanks.
This is quite weird but I did go through this video,difference between nodes and elements and it described this exact behaviour of document nodes and elements. So I got to understand the point you discussed earlier. I just didn't notice that space too is a node.

@talhaa99
Comment options

This is another way to trigger this issue:

<Head><title>{"hello"}</title></Head>

Notice the blank space after"} - subtle.

Ok I just checked my head and Yes it had the issue you described here

<Head>    <title>{`${title} - Website`} </title></Head>

I removed the extra space after the} and it works now. Thanks. This is quite weird but I did go through this video,difference between nodes and elements and it described this exact behaviour of document nodes and elements. So I got to understand the point you discussed earlier. I just didn't notice that space too is a node.

Perfect@lance1997

@t-lock
Comment options

I have this issue remaining even after I delete every and <title> in my app.... The error message generated does not help me find a line number.

@discoverlance-com
Comment options

I have this issue remaining even after I delete every and <title> in my app.... The error message generated does not help me find a line number.

Can you paste the code rendering your title?

Comment options

This solved for me -

import Head from "next/head";const siteTitle = "Site Name";// HeadSpace is the component name, so change it as you wishexport default function HeadSpace(props) {   return (    <Head>      <title>{props.pageTitle + " - " + siteTitle}</title>      <meta name="description" content={props.pageDescription} />    </Head>  );}
You must be logged in to vote
0 replies
Comment options

const name = `${title || defaultMetaData.title} | ${type || defaultMetaData.type}`return (    <Head>        <title>{name}</title> // Do this ✔✔        <title>{title || defaultMetaData.title} | {type || defaultMetaData.type}</title> // Dont do this or you get this warning ❌❌❌        <meta charSet="utf-8"/>        <meta httpEquiv="X-UA-Compatible" content="ie=edge"/>        <meta name="viewport"              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"/>        <meta name="description" content={description || defaultMetaData.description}/>        <meta itemProp="name" content={title || defaultMetaData.title}/>        <meta itemProp="description" content={description || defaultMetaData.description}/>        <meta itemProp="image" content={image || defaultMetaData.image}/>        {metaInfoTags?.map(({name, content}, index) => (            <meta key={index} property={name} content={content}/>        ))}    </Head>)

}
Warning: A title element received an array with more than 1 element as children. In browsers title Elements can only have Text Nodes as children. If the children being rendered output more than a single text node in aggregate the browser will display markup and comments as text in the title and hydration will likely fail and fall back to client rendering at title
at head
at Head (webpack-internal:///./node_modules/next/dist/pages/_document.js:127:1)
at html
at Html (webpack-internal:///./node_modules/next/dist/pages/_document.js:640:106)
at Document (webpack-internal:///./node_modules/next/dist/pages/_document.js:16:1)`

You must be logged in to vote
0 replies
Comment options

I just happened to find this warning in my console. Is there a lint rule or some other way to catch this?

You must be logged in to vote
0 replies
Comment options

thank you@icyJoseph withthis, it was the spaces in the<title> tag causing the following warning

Warning: A title element received an array with more than 1 element as children. In browsers title Elements can only have Text Nodes as children. If the children being rendered output more than a single text node in aggregate the browser will display markup and comments as text in the title and hydration will likely fail and fall back to client rendering

Before

<title>{title}</title>//     ↑       ↑// the whitespace is interpreted as 2 more text nodes

After (fixed)

<title>{title}</title>
You must be logged in to vote
0 replies
Comment options

Why not just doing it like this:

<Head>  <title>{`The best ${searchQueryParam} learning resources`}</title></Head>
You must be logged in to vote
1 reply
@icyJoseph
Comment options

Yeah, I thought I had included it. I have answered this question a few times hehe, I'll copy paste from my other answers when I get home.

Comment options

What we are all doing is workaround, it should just accept

<Head>  <title>{var} needs to be solved</title></Head>

This is clearly a bug

You must be logged in to vote
0 replies
Comment options

I had the same Warning message and Solved :

In my case, I had a Seo component and used the Head inside and had the title as a prop and had some text together like this :

import Head from 'next/head';export default function Seo({ title }) {    return (        <Head>            <title>{title}| Next Movies</title>        </Head>    );}

Due to the warning message, I had changed my Seo component using template literal(``) like below and error is gone:

import Head from 'next/head';export default function Seo({ title }) {    return (        <Head>            <title>{`${title}| Next Movies`}</title>        </Head>    );}
You must be logged in to vote
1 reply
@data-miner00
Comment options

Yup, I had the exact same issue and concatenated them together before outputting to the<Title> tag fixed the issue.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Help
Labels
None yet
24 participants
@florianwalther-private@gtwebsite@jekh@t-lock@icyJoseph@ModernHooman@pajarrahmansyah@indiabullriders@zohaibasghar@Xcalytoe@ptbarnum4@cdx111@Rosa-Kang@discoverlance-com@Asylcreek@data-miner00@GGalupo@1mehdifaraji@mudassir-jmi@talhaa99@hafizhuseynovand others

[8]ページ先頭

©2009-2025 Movatter.jp