DEV Community

Cover image for React Design Patterns~Layout Componets / Screen Splitter~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on • Edited on

React Design Patterns~Layout Componets / Screen Splitter~

  • Screen Splitter

This pattern is often used in common layouts that consist of sidebar, main, and so on.

・App.js

import { SplitScreen } from "./components/split-screen";

const LeftSide = ({ title }) => {
  return <h2 style={{ backgroundColor: "red" }}>{title}</h2>;
};

const RightSide = ({ title }) => {
  return <h2 style={{ backgroundColor: "blue" }}>{title}</h2>;
};

function App() {
  return (
    <SplitScreen leftWidth={1} rightWidth={3}>
      <LeftSide title={"Left"} />
      <RightSide title={"Right"} />
    </SplitScreen>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

・This component wraps the LeftSide and RightSide components inside the SplitScreen component as children.

・I pass title props to the LeftSide and RightSide components.

・I pass leftWidth and rightWidth props to the SplitScreen component so that I can change the width of each of the components.

・split-screen.js

import React from "react";
import { styled } from "styled-components";

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

const Panel = styled.div`
  flex: ${(p) => p.flex};
`;
export const SplitScreen = ({ children, leftWidth = 1, rightWidth = 1 }) => {
  const [left, right] = children;
  return (
    <Container>
      <Panel flex={leftWidth}>{left}</Panel>
      <Panel flex={rightWidth}>{right}</Panel>
    </Container>
  );
};
Enter fullscreen mode Exit fullscreen mode

・This component is composed of the Left and Right components, which are received as children.

・I can change the width of each of the components receiving leftWidth and rightWidth as props.

A pie chart showing 40% responded

Top comments (0)