Search code examples
javascriptnode.jsreactjsserver-side-renderingisomorphic-javascript

How to access the props from server-side rendering when re-render the component in client side?


I have done lots of research, and failed to make it work though.

It is based on express.js and react in a isomorphic application.

I used renderToString() to parse my component and send it back to client side.

let passedProps = {'foo':'bar'};

const html = ReactDOMServer.renderToString(
            React.createElement(myComponent, passedProps)
    );
res.send(renderFullPage(html, passedProps));

I gotta re-render it in client-side in order to activate the event handler.

function renderFullPage(html, passedProps) {
  return `
        <!DOCTYPE html>
        <html lang="en">
          <head>
            ........
          </head>
          <body>
            <div id="root">${html}</div>
          ......
            <script>
             function render() {
                ReactDOM.render(
                  React.createElement(
                    myComponent,
                    ${passedProps}
                  ),
                  document.querySelector('#root')
                );
             }
            render();

            </script>
          </body>
        </html>`;
}

The problem is that I want to make the client-side rendering has the same initial props {'foo':'bar'} as server-side. But it seems like I can't really pass in ${passedProps} inside of the html < script > tag, the program will skip executing the code inside, therefore the client-side rendering will not work as well.

Is there any way that I can access the passedProps in < script >?

Any kind of suggestions with be really appreciated!!


Solution

  • I have something like that in my real project:

    <script>window.__INITIAL_PROPS__ = JSON.stringify(${passed_props})</script>
    

    You're taking these props and pass them into react.js on the client side. I hope this will help you.