0

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

3
  • seems to be ok for me can you create stackblitz to reproduce the problem? Commented Dec 18, 2018 at 4:18
  • @Justcode ok, I push the file to Github, please have a look. Commented Dec 18, 2018 at 9:38
  • @jimmy, since this is server side, where is your Express application? Can you paste your Express file? Commented Feb 22, 2019 at 18:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.