Skip to content

Commit

Permalink
Handle rendering next/head outside of Next.js (#14511)
Browse files Browse the repository at this point in the history
This ensures `next/head` doesn't fail to render when being rendered during tests or outside of Next.js' tree

Closes: #14425
  • Loading branch information
ijjk committed Jun 23, 2020
1 parent 574e9d2 commit 5bb081f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
27 changes: 19 additions & 8 deletions packages/next/next-server/lib/side-effect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,42 @@ type SideEffectProps = {
}

export default class extends Component<SideEffectProps> {
private _hasHeadManager: boolean

emitChange = (): void => {
this.props.headManager.updateHead(
this.props.reduceComponentsToState(
[...this.props.headManager.mountedInstances],
this.props
if (this._hasHeadManager) {
this.props.headManager.updateHead(
this.props.reduceComponentsToState(
[...this.props.headManager.mountedInstances],
this.props
)
)
)
}
}

constructor(props: any) {
super(props)
if (isServer) {
this._hasHeadManager =
this.props.headManager && this.props.headManager.mountedInstances

if (isServer && this._hasHeadManager) {
this.props.headManager.mountedInstances.add(this)
this.emitChange()
}
}
componentDidMount() {
this.props.headManager.mountedInstances.add(this)
if (this._hasHeadManager) {
this.props.headManager.mountedInstances.add(this)
}
this.emitChange()
}
componentDidUpdate() {
this.emitChange()
}
componentWillUnmount() {
this.props.headManager.mountedInstances.delete(this)
if (this._hasHeadManager) {
this.props.headManager.mountedInstances.delete(this)
}
this.emitChange()
}

Expand Down
18 changes: 18 additions & 0 deletions test/unit/next-head-rendering.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* eslint-env jest */
import Head from 'next/head'
import React from 'react'
import ReactDOM from 'react-dom/server'

describe('Rendering next/head', () => {
it('should render outside of Next.js without error', () => {
const html = ReactDOM.renderToString(
React.createElement(
React.Fragment,
{},
React.createElement(Head, {}),
React.createElement('p', {}, 'hello world')
)
)
expect(html).toContain('hello world')
})
})

0 comments on commit 5bb081f

Please sign in to comment.