Hydration

You can use whatever server-side solution to pre-render the html for your document. Then after the page loads, you can let Composi take over parts of the document as components. To do this you need to follow a simple rule let your component know what element you want to hydrate. To do this, give your component a hydrate property and provide it with a reference to the element to hydrate.

Suppose on the server we output some markup as follows:

<body>
  <article>
    <ul id="specialList">
      <li>Apples</li>
      <li>Oranges</li>
      <li>Bananas</li>
    </ul>
  </article>
</body>

When the page first loads this will be the default content. In fact, if the JavaScript did not load or failed with an exception, the user would see this content. If we want to replace the static content with a dynamic list, we can define the list component like this:

class List extends Component {
  render(fruits) {
    return (
      <ul id="specialList">
        {
          fruits.map(fruit => <li>{fruit}</li>)
        }
      </ul>
    )
  }
}

const list = new List({
  container: 'article',
  state: ['Stawberries', 'Peaches', 'Blueberries']
  // Tell the component to hydrate the following element:
  hydrate: '#specialList'
})
          

With the above code, even though the server sent a static list to the browser, at load time Composi will replace it with the dynamic component of the same id in the same container element.

Note: When implementing serve-side rendering and component hydration, it's best to use ids for the parts you want to hydrate. That way it's easier for Composi to identify unique parts of the static HTML to take over.

Hydrating with Functional Components

If you wish to hydrate server-rendered content with functional components, you will need to use the mount function and pass it a third argument with a reference to the DOM tree to hydrate, or a valid CSS selector for that node in the DOM. Please read the docs for the mount function for more details.