React: Design Patterns | Understanding Layout Components
Published: 2024-06-04 23:04:03

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.

```javascript
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;
`;
```

### 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.

```javascript
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};
`;
```

## 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.

```javascript
export const RegularList = ({ items, resourceName, itemComponent: ItemComponent }) => {
  return (
    <>
      {items.map((item, i) => (
        <ItemComponent key={i} {...{ [resourceName]: item }} />
      ))}
    </>
  );
};
```

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

```javascript
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>
      ))}
    </>
  );
};
```

## 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.

```javascript
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;
`;
```

### 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](https://github.com/LinkedInLearning/react-design-patterns-2895130) is a course by Shaun Wassell that you can follow on LinkedIn Learning.