Layout Component and why we use it in React

Olena Drugalya - Nov 17 '20 - - Dev Community

This blog post starts a series of posts exploring React components. When a developer starts an application, he has to decide what components and for what purpose will be used.

In this blog post I will go through Layout Component - an extremely useful component in every application.

Purpose of Layout Component

This component does exactly what its name says - it defines the layout of the application. It simply accepts children as props and render them to the DOM together or without other child components.

It's a good practice to separate it from other components in the project in a separate folder like this:
Folder_layout

Usage of Layout Component

In the Layout folder we create Layout.js file and store the code of layout component there:



import React from 'react';

const Layout =({children}) =>{
    return(
        <>
        <div>
            <ToolBar/>
            <Sides/>
            <Backdrop/>
        </div>
        <main>{children}</main>
        </>
    )
}

export default Layout;


Enter fullscreen mode Exit fullscreen mode

In the main App.js file we import Layout and wrap our application with it:



import React from "react";
import Layout from "./components/Layout/Layout";

function App() {
  return (
    <>
      <Layout>
        <p>Test</p>
      </Layout>
    <>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

So we have separated layout logic into the component and if we want to change layout later, we can simple do that with changing just one component.

Reusable Layout Components

Because Layout component is so simple, it can be re-used in other parts of application, where a developer wants to use the same page layout. Moreover, it's possible to create customs reusable layouts which use FlexBox or Grid properties like this:



<Flexbox vertical gap={3}>
  <Flexbox noGrow>
    <h1>A Title for You</h1>
  </Flexbox>
  <Flexbox bottom>
    <p>Your cool paragraph.</p>
  </Flexbox>
</Flexbox>


Enter fullscreen mode Exit fullscreen mode

Working with reusable layouts is a very good practice, because it let you write code once and use it in a lot of parts of your application.

Here below are some of the reusable layout components which one can use while building applications:

1. React grid layout - demo and code
2. React Flexbox grid - code
3. React Material-UI grid - source
4. Grommet grid layout - source
5. React Bootstrap / Reactstrap grid layout - source
6. Autoresponsive React - code
7. React stack grid - demo and code
8. Hedron - code
9. React grid system - code
10. Rebass React grid - code
11. Semantic-UI React grid - source
12. Reflexbox - code

Thank you for reading my blog. Feel free to connect on LinkedIn or Twitter :)

Buy Me a Coffee at ko-fi.com

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .