How to use React.Component with renderToString method?

695 Views Asked by At

I tried to do the server side render using renderToString method.

function handleRender(req, res) {

    const html = renderToString(
        <Counter />
    );

    res.send(renderFullPage(html));
}

function renderFullPage(html) {
  return `
    <!doctype html>
    <html>
      <head>
        <title>React Universal Example</title>
      </head>
      <body>
        <div id="app">${html}</div>
        <script src="/static/bundle.js"></script>
      </body>
    </html>
    `
}

If the component like following it works:

Counter.js

const Counter = () => {

  function testClick(){
    console.log('test');
  }

  return (
    <div>
      <div onClick={testClick.bind(this)}>
        test
      </div> 
    </div>
  );

};

export default Counter;

However, if I change Counter.js into following:

class Counter extends React.Component {

    testClick(){
        console.log('click');
    }

    render() {
        return (
            <div>
                <div onClick={this.testClick.bind(this)}>
                    test btn
                </div>
            </div>
        )
    }
}

export default Counter;

It will show errors:

Uncaught Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration.

So how to use React.Component with renderToString method?


I minimize the project and push to Github. Please have a look.

https://github.com/ovojhking/ssrTest/tree/master

0

There are 0 best solutions below