44
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:
You can choose either class component or function component that works best for you 😄
const Layout = () => {
return (
<div></div>
)
}
<Layout></Layout>
const Layout = ({children}) => {
return (
<div></div>
)
}
import NavigationBar from '../components/NavigationBar'
import Footer from '../components/Footer'
const Layout = ({children}) => {
return (
<div>
<NavigationBar />
<Footer />
</div>
)
}
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.
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>
)
}
44