@composi/renderToString:

Usage

Rendering Components on the Server

Depending on whether you are rendering simple functional components or a runtime program, the usage is basically the same. If you have a functional component that you would normally output using the render function, instead just pass it to the renderToString function. It takes one argument, the component to render:

function Title({title
{
  return (
    <h1>The Title: {title}</h1>
  )
}
// Create a string version of the component:
const renderedTitle = renderToString(<Title title="We are rendering on the server!" />)

After creating a string representation of the component, you can use it with whatever server-side templating solution you are using.

When rendering a component on the server, you'll probably also want to have a dynamic version that loads on the clinet side. You can hydrate the server side version by providing a reference to it as the third value of the render function. Please read the docs for that.

Gotcha

When defining values for props, particular inline events, be aware that any values that you use should be quoted using double quotes. That's because all prop values, including events, get enclosed in single quotes.

Runtime Programs

To render a runtime program on the server, you just need to use renderToString to return the component that the view method of the program returns.. Remember that Runtime program views do not know anything about how the component is rendered. They just provide state and the send function.


function Title({state}) {
  return (
    <h1>The Title: {state}</h1>
  )
}
const state = 'We are rendering on the server!'
  const program = {
  init() {
    return [state]
  },
  view(state, send) {
    // Return a string version of the component:
    const renderedTitle = renderToString(<Title {...{state, send}} />)
    // Do whatever you need to do to put the page together here...
  },
  update(state, msg) {
    // nothing here yet...
  }
}