Rendering to strings

The aim with rendering components in Node.js is to render to strings, instead of trying to figure out the best way to insert them into the DOM. The string content is then returned to the browser, which displays this to the user immediately. Let's get our feet wet with a basic example. First, we have a simple component that we want to render:

import React, { PropTypes } from 'react'; 
 
const App = ({ items }) => ( 
  <ul> 
    {items.map(i => ( 
      <li key={i}>{i}</li> 
    ))} 
  </ul> 
); 
 
App.propTypes = { 
  items: PropTypes 
    .arrayOf(PropTypes.string) 
    .isRequired, 
}; 
 
export default App; 

Next, let's implement the server that will render this component when the browser asks for it:

import React from 'react'; // The "renderToString()" function is like ...

Get React and React Native now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.