How To Create A Layout Component: React

When creating a react application/website, most of the pages would be sharing the same content all over, other than importing each component in every page to be rendered, it is much easier and faster to just create a layout component.

Here is how to do it:

1. Create a new file called Layout.js (could be any name of choice)

2. Create a function component

You can choose either class component or function component that works best for you 😄

const Layout = () => {
 return (
  <div></div>
 )
}

3. Add a prop called children to allow the components to be used as an HTML tag with both opening and closing tags i.e

<Layout></Layout>

const Layout = ({children}) => {
 return (
  <div></div>
 )
}

4. Add all the contents/components that would be used across all pages in your react application i.e Navigation bar, Footer, styles:

import NavigationBar from '../components/NavigationBar'
import Footer from '../components/Footer'

const Layout = ({children}) => {
 return (
  <div>
    <NavigationBar />
    <Footer />
  </div>
 )
}

5. Adding the children props

Add the children props where contents from other pages will be dynamically added:

import NavigationBar from '../components/NavigationBar'
import Footer from '../components/Footer'

const Layout = ({children}) => {
 return (
  <div>
    <NavigationBar />
    <main>
      {children}
    </main>
    <Footer />
  </div>
 )
}

Now any content added within the layout component will have the same navbar and footer.

6. Using the Layout Component:

Import the component into the pages needed i.e

import Layout from '../layout/Layout'

const AboutPage = () => {

return (
  <Layout>
    //page content
  </Layout>
)

}


import Layout from '../layout/Layout'

const HomePage = () => {

return (
  <Layout>
    //page content
  </Layout>
)

}

30