Implement page title handling with SSR support using react-helmet

This commit is contained in:
Kimmo Puputti 2017-01-05 16:24:26 +02:00
parent f6755882f1
commit 83f80b6950
4 changed files with 33 additions and 22 deletions

View file

@ -2,7 +2,7 @@
<html>
<head>
<meta charset="utf-8">
<title>%-title%</title>
%=title%
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
</head>

View file

@ -1,3 +1,5 @@
require('source-map-support').install();
const express = require('express');
const path = require('path');
const fs = require('fs');
@ -24,10 +26,11 @@ const template = _.template(indexHtml, {
evaluate: /($^)/
});
function render(url, context, title) {
function render(url, context) {
const { head, body } = renderApp(url, context)
return template({
title,
body: renderApp(url, context)
title: head.title.toString(),
body
});
}
@ -37,12 +40,8 @@ const app = express();
app.use('/static', express.static(path.join(buildPath, 'static')));
app.get('*', (req, res) => {
// TODO: use react-helmet for metadata handling
const title = 'Sharetribe Starter <b>App</b>';
const context = createServerRenderContext();
const html = render(req.url, context, title);
const html = render(req.url, context);
const result = context.getResult();
if (result.redirect) {

View file

@ -1,9 +1,11 @@
import React from 'react';
import Helmet from 'react-helmet';
export default (props) => {
const { className, title, children } = props;
return (
<div className={ className }>
<Helmet title={ title } />
<h1>{ title }</h1>
{ children }
</div>

View file

@ -1,23 +1,33 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { renderToString } from 'react-dom/server';
import ReactDOMServer from 'react-dom/server';
import Helmet from 'react-helmet';
import { BrowserRouter, ServerRouter } from 'react-router';
import Routes from './Routes';
import './index.css';
const ClientApp = () => (
<BrowserRouter>
<Routes />
</BrowserRouter>
);
const ServerApp = (props) => (
<ServerRouter { ...props } >
<Routes />
</ServerRouter>
);
if (typeof window !== 'undefined') {
ReactDOM.render(
<BrowserRouter>
<Routes />
</BrowserRouter>,
document.getElementById('root')
);
ReactDOM.render(<ClientApp />, document.getElementById('root'));
}
export default function render(url, serverContext) {
return renderToString(
<ServerRouter location={ url } context={ serverContext }>
<Routes />
</ServerRouter>
const renderApp = (url, serverContext) => {
const body = ReactDOMServer.renderToString(
<ServerApp url={ url } context={ serverContext }/>
);
}
const head = Helmet.rewind();
return { head, body };
};
export default renderApp;