Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to avoid "Text content did not match" warning in SSR with React?

I have set up a SSR environment with webpack and HMR. There is a statically rendered markup, that server passes to the client and a client.js bundle with ReactDOM.hydrate() method. If I change my source code, HMR works fine, but issues a warning in console, saying that there's a mismatch between client code and static markup.

I am using an express server with webpack-dev-middleware and webpack-hot-middleware

My webpack config looks like this:

module.exports = {
  mode: 'development',
  entry: ['webpack-hot-middleware/client', './src/client.js'],
  devServer: {
    hot: true,
    publicPath: '/'
  },
  plugins: [new HotModuleReplacementPlugin()],
  module: {
    rules: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader' }]
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  output: {
    filename: 'client.js',
    path: path.resolve(__dirname)
  }
};

I'm wondering if there is any way to solve this problem, since I can't come up with any ideas of how to make my markup to match the changes that I made, or should I just suppress these warnings?

like image 495
Oscar Avatar asked Dec 28 '18 14:12

Oscar


People also ask

Is it possible to make a contenteditable block with react?

A contentEditable block makes changes to the DOM that aren't tracked by React. So maybe the best thing to do is to use React as a "portal" into a non-React-managed contentEditable like so:

What is the purpose of wrapping a contenteditable Div in react?

The wrapping contenteditable div allows the 2 internal spans to be styled independently but for the pair to behave as one "textbox" kinda thing. Sometimes I have hundreds of these structures rendering in my app, each one triggering a warning from React: "A component is contentEditable and contains children managed by React.

Why is it bad to re-render a React component with jQuery?

This is bad because it causes React's internal DOM representation to be out of sync with the actual DOM, and re-rendering can cause unexpected changes. His specific use case is wrapping jQuery libs in a portal, because jQuery libs like to manipulate the DOM.

Why doesn't the HTML rendered on the browser match the server?

The HTML rendered on the browser doesn’t match the one generated on the server because cook.get ("key") returns different things in both. To solve it you can move setting the state inside a useEffect. react-cookie or next-universal-cookie instead.


1 Answers

If you set suppressHydrationWarning to true, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch.

<MyComponent suppressHydrationWarning />

More info at https://reactjs.org/docs/dom-elements.html#suppresshydrationwarning

like image 148
untitled Avatar answered Nov 09 '22 12:11

untitled