Last active
December 5, 2015 15:14
-
-
Save jcblw/4419aad6fc36073a88f3 to your computer and use it in GitHub Desktop.
React Component Server API proposal.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is the main layout file | |
// essentially the default export is a function which is passed content (as a string) | |
// and an object which can contain a number of things eg. props, and some meta data about the request | |
import React from 'react' | |
import {safeStringify} from 'react-component-server' | |
export default (content, {props}) => { | |
return ( | |
<html> | |
<head> | |
<title>props.title</title> | |
<meta charSet='utf8' /> | |
</head> | |
<body> | |
<div id='app' dangerouslySetInnerHTML={{ | |
__html: content | |
}} /> | |
<script src={`/js/${props.scriptName}.js`} /> | |
<script dangerouslySetInnerHTML={{ | |
__html: ` | |
var app = require('app') | |
app(${safeStringify(props)}) | |
` | |
}} /> | |
</body> | |
</html> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sample of how the api could look | |
// this is setting up the server, putting in some routes and configuring them. | |
import ComponentServer from 'react-component-server' | |
const port = process.env.PORT || 3000 | |
const componentServer = ComponentServer.create({ | |
server: server, // optionally pass in own express server | |
componentsDir: './components', // path to components | |
precompile: ['/explore', '/manage'], // paths to precompile | |
templatesDir: './templates', // templates | |
doctype: '<!doctype html>', // doctype this is the default, but it could be changed here | |
defaults: { | |
component: './Home', | |
props: {}, | |
template: './_layout' | |
} | |
}) | |
// registers path just passes defaults | |
componentServer.get('/') | |
// pass in a config object to second argument | |
componentServer.get('/explore', { | |
component: './Explore', | |
props: { | |
defaultText: 'Santa Monica, Ca' | |
}, | |
template: './_layout' | |
}) | |
// register a function to allow for async operations to happen | |
componentServer.get('/manage', (req, done) => { | |
done({ | |
component: './Manage' | |
}) | |
}) | |
// listen to port | |
componentServer.listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment