0

I'm obviously missing something here. I have a simple React class that I want to convert to using Server Side Rendering but I can't get the initial component to render on the server.

I've altered my initial App class to use renderToString

const App = ()=> {    
  var html = ReactDOMServer.renderToString(<div>
         <div className="jumbotron text-center">
           <h1>Welcome!</h1>
         </div>
         <div className="container">
           <MyComponent />
         </div>
       </div>);
   return html;
}

export default App;

I've updated the index.js file to use hydrate:

ReactDOM.hydrate(<App />, document.getElementById('root'));

I don't, however, get MyComponent rendered in the browser. What I get is the HTML for MyComponent displayed in the browser page. If, in the browser, I look at the page source, I can see that the component's HTML isn't being downloaded with the page (the root element used in hydrate is empty). When I use the Developer's Tools elements tab, I can see all of my component's HTML has been inserted into the root element inside a quoted string (which is why it's displayed in the browser page).

I'm assuming that's what's happening is that my component is not being rendered on the server but is still being invoked from the browser. The result is that my renderToString is returning a string to the client of all of my component's HTML which hydrate dutifully inserts into my root element.

What am I missing here? I created the application with npx create-react-app and am using version 16.8.0.

5
  • Do you have a server setup to do so? Post a version of your servercode too? Oct 7, 2020 at 9:34
  • Not sure what you mean by servercode? Are there specific configuration files, for example, that you're looking for? If it's any help: This is a vanilla React application running in Visual Studio Code using the development server that comes with the npx package. Oct 8, 2020 at 10:08
  • You need to create a server to have server-side rendering. Look at this -> flaviocopes.com/react-server-side-rendering. You need to have a server listening out for a request the throws React when called upon. Oct 8, 2020 at 10:47
  • That sounds like the kind of thing that I'm missing. And you're saying that the development server set up with npx isn't set up that way by default and/or additional code is required to integrate with that server. Oct 9, 2020 at 10:17
  • Nope. You need to create your own server or you could use Nextjs for server side rendering in React. Oct 9, 2020 at 13:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy