Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 4005

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T07:59:08+00:00 2024-11-26T07:59:08+00:00

πŸš€ Transform Your UI: Creating Layouts Using Compound Components in React – A Step-by-Step Guide

  • 61k

Introduction

Building robust and maintainable layouts can be a challenge in React applications. Compound components offer a way to achieve this by allowing for reusable and modular code. In this tutorial, you'll learn how to create a layout using compound components step by step by leveraging the concept of slots.

The Goal

const App = () => {   return (     <MainLayout.Root>       <MainLayout.Sidebar className="shadow-xl z-10 relative">         <p>Sidebar</p>       </MainLayout.Sidebar>       <MainLayout.Header>         <h1 className="text-xl font-bold">My App</h1>       </MainLayout.Header>       <MainLayout.Body>         <p>Body</p>       </MainLayout.Body>       <MainLayout.Footer>         <p>Footer</p>       </MainLayout.Footer>     </MainLayout.Root>   ); }; 
Enter fullscreen mode Exit fullscreen mode

Why Slots?

Before diving into the code, it's crucial to understand what slots are and why we're using them. A slot is just a placeholder where other components can be inserted.

For our layouts we'll be defining two types of slots: a fragment slot and a container slot. The fragment slot prevents the caller from setting any properties, such as className, whereas the container slot allows it. This flexibility lets us control how our layout behaves and is customized.

Create a Fragment Slot

The fragment slot is a simple wrapper that renders its children without adding any additional HTML tags or properties. This kind of slot is beneficial when you want to maintain a clean and controlled structure.

export const Slot = () => (props: { children: React.ReactNode }) => {   return <>{props.children}</>; }; 
Enter fullscreen mode Exit fullscreen mode

Create a Container Slot

The container slot is more versatile and can behave like any HTML tag, such as a div, section, header, etc. This allows for more customization and control. We define a className argument so that we can provide some default classes.

export const ContainerSlot =   (ar?: {     as?: "div" | "section" | "header" | "footer" | "main";     className?: string;   }) =>   (props: { children: React.ReactNode } & HTMLProps<HTMLDivElement>) => {     const El = ar?.as ?? "div";     return (       <El {...props} className={cn(ar?.className, props.className)}>         {props.children}       </El>     );   }; 
Enter fullscreen mode Exit fullscreen mode

These two slots are the only ones we need for our example but we've also found it useful to create other slots like a “Text” slot that required props.children to be a string.

Getting our slot content

In order to get our slot content when we're defining our layout we need to loop through our props.children using something like React.Children.map but for convenience we'll just use a library react-nanny. You can leave this out if you don't want another dependency.

import { getChildrenByType } from "react-nanny";  export const getSlotByType = (   children: React.ReactNode | undefined | null,   type: React.ElementType | React.ElementType[] ) => {   if (!children) return null;   const content = getChildrenByType(children, type);   return content; }; 
Enter fullscreen mode Exit fullscreen mode

Define our layout

Let's define our layout sections and layout. We'll create slots for a sidebar, header, footer, and main content area.

const Sidebar = ContainerSlot({   className: "bg-gray-100 w-64 flex flex-col overflow-hidden", });  const Header = ContainerSlot({   className: "bg-gray-100 flex items-center justify-between px-4 py-2",   as: "header", });  const Footer = ContainerSlot({   className: "bg-gray-100 flex items-center justify-between px-4 py-2",   as: "footer", });  const Body = ContainerSlot({   className: "flex-1 overflow-auto",   as: "main", });  const Root = (props: { children: React.ReactNode }) => {   // Here we're using our util to get the appropriate slot content   const sidebar = getSlotByType(props.children, Sidebar);   const header = getSlotByType(props.children, Header);   const footer = getSlotByType(props.children, Footer);   const body = getSlotByType(props.children, Body);    return (     <div className="flex flex-col h-screen w-screen">       {header}       <div className="flex flex-1">         {sidebar}         {body}       </div>       {footer}     </div>   ); };  export const MainLayout = {   Root,   Sidebar,   Header,   Footer,   Body, }; 
Enter fullscreen mode Exit fullscreen mode

Use the layout

We can now use the layout in our application

const App = () => {   return (     <MainLayout.Root>       <MainLayout.Sidebar>         <p>Sidebar</p>       </MainLayout.Sidebar>       <MainLayout.Header>         <h1 className="text-xl font-bold">My App</h1>       </MainLayout.Header>       <MainLayout.Body>         <p>Body</p>       </MainLayout.Body>       <MainLayout.Footer>         <p>Footer</p>       </MainLayout.Footer>     </MainLayout.Root>   ); }; 
Enter fullscreen mode Exit fullscreen mode

Conclusion

That's it! We've created a reusable layout using compound components. Feel free to explore these concepts further and adapt them to your specific needs.

frontendreacttutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.