React: Design Patterns | Understanding Layout Components

andresz74

Andres Z

Posted on June 4, 2024

React: Design Patterns | Understanding Layout Components

Layout components in React are specialized components designed to arrange other components on a page. Their primary role is to manage the layout, allowing the main content components to remain agnostic about their placement. This separation of concerns enhances flexibility and reusability. Examples include split screens, lists, and modals.

Split-Screen Components

A split-screen component divides the screen into two sections, each displaying a different component. Here's how you can create one:

  1. Define the Component: Create a new file, SplitScreen.js, and define the component with left and right props.
  2. Structure the Layout: Use a container div to hold two child divs for the left and right components.
  3. Style the Layout: Use styled-components to apply flexbox styles, ensuring both sides take up equal space.
import styled from 'styled-components';

export const SplitScreen = ({ left: Left, right: Right }) => {
  return (
    <Container>
      <Pane><Left /></Pane>
      <Pane><Right /></Pane>
    </Container>
  );
};

const Container = styled.div`
  display: flex;
`;

const Pane = styled.div`
  flex: 1;
`;
Enter fullscreen mode Exit fullscreen mode

Enhancing Split-Screen Components

To make the split-screen component more flexible, you can add weight props to control the space each side occupies:

  1. Add Weight Props: Introduce leftWeight and rightWeight props with default values.
  2. Apply Weights: Pass these weights to the styled components and adjust the flex property accordingly.
export const SplitScreen = ({ left: Left, right: Right, leftWeight = 1, rightWeight = 1 }) => {
  return (
    <Container>
      <Pane weight={leftWeight}><Left /></Pane>
      <Pane weight={rightWeight}><Right /></Pane>
    </Container>
  );
};

const Pane = styled.div`
  flex: ${props => props.weight};
`;
Enter fullscreen mode Exit fullscreen mode

Lists and List Items

Lists are another common layout pattern. You can create reusable list components that display different types of items:

  1. Define List Items: Create small and large list item components for different data types (e.g., people, products).
  2. Create a Regular List: A generic list component that takes items, a resource name, and an item component as props.
export const RegularList = ({ items, resourceName, itemComponent: ItemComponent }) => {
  return (
    <>
      {items.map((item, i) => (
        <ItemComponent key={i} {...{ [resourceName]: item }} />
      ))}
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

Numbered Lists

To create a numbered list, extend the regular list component to include item numbers:

export const NumberedList = ({ items, resourceName, itemComponent: ItemComponent }) => {
  return (
    <>
      {items.map((item, i) => (
        <React.Fragment key={i}>
          <h3>{i + 1}</h3>
          <ItemComponent {...{ [resourceName]: item }} />
        </React.Fragment>
      ))}
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

Modal Components

Modals are used to display content over the main page. Here's how to create a simple modal component:

  1. Define the Modal: Create a new file, Modal.js, and define the modal component with state management for visibility.
  2. Structure the Modal: Use styled-components for the modal background and body.
  3. Toggle Visibility: Add buttons to show and hide the modal.
import React, { useState } from 'react';
import styled from 'styled-components';

export const Modal = ({ children }) => {
  const [shouldShow, setShouldShow] = useState(false);

  return (
    <>
      <button onClick={() => setShouldShow(true)}>Show Modal</button>
      {shouldShow && (
        <ModalBackground onClick={() => setShouldShow(false)}>
          <ModalBody onClick={e => e.stopPropagation()}>
            {children}
            <button onClick={() => setShouldShow(false)}>Hide Modal</button>
          </ModalBody>
        </ModalBackground>
      )}
    </>
  );
};

const ModalBackground = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
`;

const ModalBody = styled.div`
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
`;
Enter fullscreen mode Exit fullscreen mode

Conclusion

Layout components in React help manage the arrangement of other components on a page. By separating layout concerns from content concerns, you gain flexibility and reusability in your codebase. Whether you're creating split screens, lists, or modals, understanding and utilizing layout components can significantly enhance your development workflow.


React: Design Patterns is a course by Shaun Wassell that you can follow on LinkedIn Learning.

💖 💪 🙅 🚩
andresz74
Andres Z

Posted on June 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related