Server side rendering

This guide covers server side rendering with custom server, Next.js and Gatsby usage guides are available separately.

  1. Install @mantine/ssr package
yarn add @mantine/ssr
npm install @mantine/ssr
  1. Create App component with MantineProvider
import { Button, MantineProvider } from '@mantine/core';
export function App() {
return (
{/* Setup MantineProvider with your theme */}
<MantineProvider theme={{ colorScheme: 'dark' }}>
<Button>My awesome app</Button>
</MantineProvider>
);
}
  1. Create Html component for page rendering
// Most basic html component – in real app you will need something more complex
export function Html({ children, styles }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{/* We will inject extracted styles here */}
{styles}
</head>
<body>
<div id="app" dangerouslySetInnerHTML={{ __html: children }} />
</body>
</html>
);
}
  1. Setup ssr middleware (example with express):
import { renderToStaticMarkup, renderToString } from 'react-dom/server';
import express from 'express';
import { createStylesServer, ServerStyles } from '@mantine/ssr';
import { App } from './App';
import { Html } from './Html';
const stylesServer = createStylesServer();
app.use('*', (req, res) => {
// Render App to string first to capture styles that should be extracted
const content = renderToString(<App />);
const html = renderToStaticMarkup(
// ServerStyles will return <style> tag with extracted styles
<Html styles={<ServerStyles html={content} server={stylesServer} />}>{content}</Html>
);
res.send(`<!doctype html>\n${html}`);
});
Build fully functional accessible web applications faster than ever
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback