Skip to content

dangerouslySetInnerHTML, children, and a bogus hydration warning #17170

@jaydenseric

Description

@jaydenseric

Do you want to request a feature or report a bug?

Bug (initially reported at vercel/next.js#9173).

What is the current behavior?

If a component has both dangerouslySetInnerHTML and children props, and the component is used with just the children prop, on page load the client logs a warning beginning with Warning: Prop `dangerouslySetInnerHTML` did not match..

Interestingly:

  • If just dangerouslySetInnerHTML is used there is no warning.
  • Multiple instances with just a children prop results in only one warning, for the first occurance.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

Demo: https://codesandbox.io/s/react-hydration-warning-demo-3je59

In a Next.js project, create a page with the following content:

const TestComponent = ({ dangerouslySetInnerHTML, children }) => (
  <div dangerouslySetInnerHTML={dangerouslySetInnerHTML} children={children} />
)

export default () => <TestComponent>a</TestComponent>

Loading the page in a browser will result in this warning logging to the console:

Warning: Prop `dangerouslySetInnerHTML` did not match. Server: "a" Client: ""

Note that the hydration warning is bogus; using view source and the inspector you can see the SSR and client rendered HTML is identical and correct.

This works just the same as before but without a hydration warning:

const TestComponent = ({ dangerouslySetInnerHTML, children }) => {
  const divProps = {}
  if (dangerouslySetInnerHTML)
    divProps.dangerouslySetInnerHTML = dangerouslySetInnerHTML
  if (children) divProps.children = children

  return <div {...divProps} />
}

What is the expected behavior?

There should be no hydration warning at first client render.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

Not sure if the bug is present in old versions of React, but it can be seen with v16.11.0.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions