score:1

to pass the title to your app component server side, you have to pass it the same way as you're passing the path, i.e. as props and not state.

so first you'll need to change:

<title>{@state.title}</title>

to:

<title>{@props.title}</title>

then in your backend pass the wanted title to the app component when instantiating it, like so:

var url = require('url');
var reactasync = require('react-async');

var app = require('./path/to/your/root-component.jsx');

// app = your express app:
app.get('*', function (req, res) {
  var path = url.parse(req.url).pathname;
  var title = gettitlefrompath(path); // made up function to get title from a path..
  reactasync.rendercomponenttostringwithasyncstate(
    app({path: path, title: title}),
    function (err, markup) {
      if (err) return res.send(500, err);
      res.send('<!doctype html>\n' + markup);
    }
  );
});

hope that helps!

as for setting the title client side i think your solution with setting the document.title probably is the best option.

update

i've now tested the above and the title is set correctly, however react gets a different checksum for the server generated component and the client generated one, which is no good:

uncaught error: invariant violation: you're trying to render a component to the document using server rendering but the checksum was invalid

so actually you shouldn't use this solution!

will have to play around a little more...

score:2

top-level react component

var react = require('react');
var appstore = require('../stores/appstore');

var application = react.createclass({

  proptypes: {
    path: react.proptypes.string.isrequired,
    onsettitle: react.proptypes.func.isrequired
  },

  render() {
    var page = appstore.getpage(this.props.path);
    this.props.onsettitle(page.title);
    return (
      <div classname="container">
        <h1>{page.title}</h1>
        <div return <div dangerouslysetinnerhtml={{__html: page.body}}>;
      </div>
    );
  }
});

module.exports = application;

client-side startup script (entry point)

var react = require('react');
var dispatcher = require('./core/dispatcher');
var application = require('./components/application');

dispatcher.register((payload) => {
  var action = payload.action;
  if (action.actiontype === actiontypes.change_location) {
    app.setprops({path: action.path});
  }
});

var app = react.createelement(application, {
  path: window.location.pathname,
  onsettitle: (title) => document.title = title
}));
app = react.render(app, document.body);

more info: https://gist.github.com/koistya/24715d295fbf710d1e24
demo project: https://github.com/kriasoft/react-starter-kit


Related Query

More Query from same tag