I have a Reactjs application built on a Node/Express server. I am doing server side rendering via something like:
route.js
var Group = require('./react/component/groups');
var props = {foo: 'bar'};
var groupHtml = React.renderToString(Group(props));
res.render('index.ejs', {
reactOutput: groupHtml,
jsonProps: JSON.stringify(props),
start: 'lessonlist'
});
index.ejs
<div id="react-main-mount"><%- reactOutput %></div>
<script id="props" type="application/json"><%- jsonProps %></script>
<script src="/js/<%= start %>.js"></script>
This works really great! But here is my problem: One of my pages/components will have a child component. But this child component can be one of 50+ different components.
I assume I could Require every single component, even though only one will be used. This seems like a bad idea since my main.js file will be huge.
I tried sending it via a prop and JSON.stringify. This works on the server rendering to HTML, but this doesn't work on the client side because JSON.stringify can't stringify a react component.
I though I might be able to do an API call and return it, but same problem as above.
Is there any way to dynamically require something, say based off a variable like require('components/' + this.props.foo) after the I've browserified/reactified?
Any suggestions/answers would be greatly appreciated
Browserify had always been too bulky for me, so I did my research and found RequireJS. It allowed me to require other files on the client just like how Node does it.
It was difficult for me to get started with Require, but once I got it working, everything just seemed easier. See this example I wrote in CoffeeScript.
Remember to have below code at the top of every isomorphic component so you don't stumble upon the problem I had with Node not understanding the keyword define.
if typeof define != 'function'
define = require('amdefine')(module)
define (require) ->
Above code is written in coffeescript.
Let me know if more information is needed.