Table of Contents

About

React Layout / Composition -

There is three methods to create a composite component from html component / or composite

Parent components can interact with their children:

  • via props
  • but also Refs (They provide a way to access DOM nodes or React elements created in the render method)

Methods

Layout as a Higher Order Component

Layout as a Higher Order Component (decorator)

  • The Layout as High component Component
import Header from './Header'

const layoutStyle = {
  margin: 20,
  padding: 20,
  border: '1px solid #DDD'
}

const withLayout = Page => {
  return () => (
    <div style={layoutStyle}>
      <Header />
      <Page />
    </div>
  )
}

export default withLayout
  • All pages
import withLayout from '../components/MyHocLayout'

const Page = () => <p>Hello World</p>

export default withLayout(Page)

Layout as component with a prop

import Header from './Header'

const layoutStyle = {
  margin: 20,
  padding: 20,
  border: '1px solid #DDD'
}

const Layout = props => (
  <div style={layoutStyle}>
    <Header />
    {props.content}
  </div>
)

export default Layout
import Layout from '../components/MyContentLayout.js'

const indexPageContent = <p>Hello World</p>

export default function Index() {
  return <Layout content={indexPageContent} />
}

Layout with a props.children

example props.children

a WelcomeDialog is a special case of Dialog

  • The Base Components using the children props which makes it a container.
function Dialog(props) {
  return (
    <div className="dialog">
      <h1 className="Dialog-title">
        {props.title}
      </h1>
      <p className="Dialog-message">
        {props.message}
      </p>
      {props.children}
    </div>
  );
}
  • The CSS
.dialog {
      border: 1px solid black;
      padding: 10px;
}
  • The specialized
function WelcomeDialog() {
  return (
    <Dialog
      title="Welcome"
      message="Thank you for being you!" >
      <p>You are worth the whole world</p>
      </Dialog>
  );
}
  • The standard render and HTML placeholder
ReactDOM.render(
  <WelcomeDialog />,
  document.getElementById('root')
);
<div id="root"></div>

example props.children on 2 pages

import Header from './Header'

const layoutStyle = {
    margin: 20,
    padding: 20,
    border: '1px solid #DDD'
}

const Layout = props => (
    <div style={layoutStyle}>
        <Header />
        {props.children}
    </div>
)

/** This format works also
export default ({ children }) => (
  <div style={layoutStyle}>
    {children}
  </div>
)
*/

export default Layout
  • A page with this layout
import Layout from '../components/MyLayout.js'

export default function Index() {
  return (
    <Layout>
      <p>Hello World</p>
    </Layout>
  )
}

Documentation / Reference