Let's assume that if we need a different layout for every component, such as the home page, there should be two columns, and other pages should have one column, but they both share common assets such as headers and footers.
Here is the layout mock-up of our app:
OK, so now let's create our main layout:
var PageLayout = React.createClass({ render: function() { return ( <div className="container"> <h1>Welcome to EIS</h1> <hr/> <div className="row"> <div className="col-md-12 col-lg-12"> {this.props.children} </div> </div> </div> ) } })
In the preceding code, we have created the main layout for our app that handles the child layout components with this.props.children
instead of a hard-coded component. Now we'll create child components that are rendered in our main layout component:
var RightSection = React.createClass({ render: function() { return ( <div className="col-sm-9 profile-desc" id="main"> <div className="results"> <PageTitle/> <HomePageContent/> </div> </div> ) } }) var ColumnLeft = React.createClass({ render: function() { return ( <div className="col-sm-3" id="sidebar"> <div className="results"> <LeftSection/> </div> </div> ) } })
In the preceding code, we have created two components, RightSection
and ColumnLeft
, to wrap and divide our components in different sections.
So it should be easy for us to manage the layout in a responsive design:
var LeftSection = React.createClass({ render: function() { return ( React.DOM.ul({ className: 'list-group' }, React.DOM.li({className:'list-group-item text-muted'},'Profile'), React.DOM.li({className:'list-group-item'}, React.DOM.a({className:'center-block text-center',href:'#'},'Image') ), React.DOM.li({className:'list-group-item text-right'},'2.13.2014', React.DOM.span({className:'pull-left'}, React.DOM.strong({className:'pull-left'},'Joining Date') ), React.DOM.div({className:'clearfix'}) )) ) } }) var TwoColumnLayout = React.createClass({ render: function() { return ( <div> <ColumnLeft/> <RightSection/> </div> ) } }) var PageTitle = React.createClass({ render: function() { return ( <h2>Home</h2> ); } });
In the preceding code, we have split our components into two sections: <ColumnLeft/>
and <RightSection/>
. We have given the reference of both components in the <TwoColumnLayout/>
component. In the parent component, we have this.props.children
as a prop, but it only works when components are nested and React is responsible for filling this prop automatically. this.props.children
will be null if the components aren't parent components.