mildrenben
mildrenben

Reputation: 3757

Is it possible to pre render server side code with Express and React?

I have a simple Pokedex site, so it's all static content.

In an effort to learn some new things, I've built it with React, Express, Node and Redis. The pages are rendered server side. Express takes the slug, gets the data from Redis and passes it on to React.

React is basically a glorified templating language in my build which I know isn't really the best use for React as I don't get to use states etc.

Is it possible to loop through all the pokemon as if I was requesting the url and save the outputted HTML as it's own page?

It would make the pages load faster but also minimise the amount of work the server has to do, saving money and load. It's also unnecessary as the pikachu page is always the same, as are all the other mons. I get that I may have built this the wrong way, but I'm curious if this is possible.

Upvotes: 2

Views: 978

Answers (1)

rossipedia
rossipedia

Reputation: 59367

Yes. This is possible by calling ReactDOMServer.renderToStaticMarkup:

Similar to renderToString, except this doesn't create extra DOM attributes such as data-react-id, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.

You would use some code like the following:

var React = require('react');
var ReactDOMServer = require('react-dom/server');
var Component = require('./MyComponent');

var output = ReactDOMServer.renderToStaticMarkup(
  React.createElement(
    Component, {
      prop1: 'value'
    }
  )
);

or if you're using JSX:

var React = require('react');
var ReactDOMServer = require('react-dom/server');
var Component = require('./MyComponent');

var output = ReactDOMServer.renderToStaticMarkup(
  <Component prop1="value" />
);

(note that this is just sample code meant to demonstrate how to call the renderToStaticMarkup method).

Upvotes: 1

Related Questions