Creating a Layout Component
Most apps have the same layout, shared structure like navigation elements
Create a layout for the page
Creates a layout.js file in the root
The concept (pseudocode):
import Router from 'ampersand-router'
import PublicPage from './pages/public'
import ReposPage from './pages/repos'
import React from 'react'
//++++ 1. import the layout file
import Layout from './layout'
export default Router.extend({
//++++ 2. in React a component can include anotherone
renderPage () {
<Layout>
{page}
</Layout>
}
routes: {
'':'public',
'repos': 'repos'
},
public () {
React.render(<PublicPage/>, document.body)
},
repos () {
React.render(<ReposPage/>, document.body)
}
})
// ++++ 1. create layout.js in root dir
import React from 'react'
// ++++ 2. create the component
export default React.createClass({
render () {
return (
// paste the layout html stuff here...
// ++++ 3. the layout includes:
{this.props.children}
)
}
})
{this.props.children}
is the key to insert content into the layout. <Layout>{page}</Layout>
->
{page}
will be inserted into this.props.children
setting default options (ES6) for renderPage in router:
import //...
export default Router.extend({
// ++++ 1. pass the page and add default options (ES6 syntax)
renderPage (page, opts = {layout:true}) {
// ++++ 2. select to add layout or not
if(opts.layout){
// redefine page here (if layout)
page =( <Layout>
{page}
</Layout>
)
}
// ++++ 3. call render
React.render(page, document.body)
}
routes: {
'':'public',
'repos': 'repos'
},
public () {
// ++++ 4. We can now just call renderPage
this.renderPage(<PublicPage/>, {layout:false})
},
repos () {
// ++++ 4. We can now just call renderPage
this.renderPage(<ReposPage/>)
}
})
He advises to ALWAYS use an options object, not just pass booleansif statements
you have to do it outside the JSX
//...
React.createClass({
render () {
let something
if (someCondition) {
something = <div></div>
}
}
return (
<div>
{something}
<h1>...</h1>
)
})