Next.js: Why does the `Head` component need to be wrapped in a `div`?

Created on 26 Oct 2016  路  5Comments  路  Source: vercel/next.js

From the README.md:

<head> side effects

We expose a built-in component for appending elements to the <head> of the page.

import React from 'react'
import Head from 'next/head'
export default () => (
  <div>
    <Head>
      <title>My page title</title>
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    </Head>
    <p>Hello world!</p>
  </div>
)

Why does the Head component need to be wrapped in a div? Maybe I'm missing something but that seems very strange considering its final destination is within the head element.

Most helpful comment

Remember, JSX is just JavaScript, so:

return (
    <Head>...</Head>
    <p>Hello</p>
)

Is the same as:

return (
  React.createElement(Head)
  React.createElement('p', null, 'Hello')
)

You can't return two function calls in JavaScript.

All 5 comments

This is a limitation with the current way that React works in that you have to return one parent component.

React Fiber may change this though so you could do what you describe..

Exactly, it's not just the <Head> that's wrapped in a div, but also the <p> element.

You can't return more than a single element in React currently, so you need to wrap them in something.

Bad:

return (
    <Head>...</Head>
    <p>Hello</p>
);

Good:

return (
    <div>
        <Head>...</Head>
        <p>Hello</p>
    </div>
);

This has been under pretty heavy deliberation for quite some time in the React community. >> https://github.com/facebook/react/issues/2127

Remember, JSX is just JavaScript, so:

return (
    <Head>...</Head>
    <p>Hello</p>
)

Is the same as:

return (
  React.createElement(Head)
  React.createElement('p', null, 'Hello')
)

You can't return two function calls in JavaScript.

@nickcolley @mmmeff @hnordt right, thanks!

Gotcha, thanks for the edification. :+1:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

formula349 picture formula349  路  3Comments

pie6k picture pie6k  路  3Comments

lixiaoyan picture lixiaoyan  路  3Comments

irrigator picture irrigator  路  3Comments

knipferrc picture knipferrc  路  3Comments