[Solved] Next.js - Warning: A title element received an array with more than 1 element as children.
Have you ever received a warning message that says "Warning: A title element received an array with more than 1 element as children" when working with titles in Next.js or another React framework.
In this article, we will explore what I learned from icyJoseph
What causes the warning?
This warning is caused when an element in your React code is rendered with an array containing more than one element as children. For example, consider the following code:
constHome:NextPage = () => {
const world = "World";
return (
<div>
<span>Hello {world} foo</span>
</div>
);
};
React actually renders:
<div><span>Hello <!-- -->World<!-- --> foo</span></div>
He clarifies that :
That's a div with a span child, with 0 children elements, but 5 nodes as children. There's a subtle difference between elements and nodes. Here's a handy video. The 5 nodes are, text, comment, text, comment, text. The same is happening to your title element.
Such a simple yet insightful explanation.
How to fix the warning
The fix for this warning is to ensure that your element has only one child, which should be a single string. You can accomplish this by concatenating your string with any variables outside of the JSX element. Here's an example of how to fix the previous code:
constHome:NextPage = () => {
const world = "World";
const message = `Hello ${world} foo`;
return (
<div>
<span>{message}</span>
</div>
);
};
Which outputs:
<div><span>Hello World foo</span></div>
Now the span has only one, text, child node.
Thank you to icyJoseph for providing a brilliant answer to this question about the warning message.
Warning: A title element received anarray with more than 1 elementas children. In browsers title Elements can only have Text Nodesas children. If the children being rendered output more than a single text node in aggregate the browser will display markupand commentsas text in the titleand hydration will likely failand fall back to client rendering at title at head atHead (webpack-internal:///./node_modules/next/dist/pages/_document.js:282:1) at html atHtml (webpack-internal:///./node_modules/next/dist/pages/_document.js:685:104) at Document
His explanation of the difference between elements and nodes and how to fix the warning was clear and concise.
← Go home