24
14

More than 5 years have passed since last update.

styled-components で視覚的にわかりやすい Grid Layout を生成する

Posted at

https://mizchi-sandbox.github.io/grid-generator/ でやってることを、視覚的に指定できるように styled-components のヘルパ作ったら個人的に便利だったので紹介。

実装

こういうヘルパを書いた

Grid.js
import styled from 'styled-components'

export const Grid = styled.div`
  display: grid;
  grid-template-columns: ${({ columns }) => columns.join(" ")};
  grid-template-rows: ${({ rows }) => rows.join(" ")};
  grid-template-areas: ${({ areas }) =>
    areas.map(r => `'${r.join(" ")}'`).join(" ")};
  width: 100%;
  height: 100%;
`

export const GridArea = styled.div`
  grid-area: ${p => p.name};
  width: 100%;
  height: 100%;
`

使い方

MyComponent.js
// ...
import { Grid, GridArea } from './Grid'
export function MyComponent() {
  return (
    // prettier-ignore
    <Grid
      columns={["250px", "1fr"]}
      rows={[
        "40px",
        "1fr"
      ]}
      areas={[
        ["header", "header"],
        ["menu",   "editor"],
      ]}
    >
      <GridArea name="header">
        Header
      </GridArea>
      <GridArea name="menu">
        Menu
      </GridArea>
      <GridArea name="editor">
        Editor
      </GridArea>
    </Grid>
  )
}

columns と rows と areas で二次元的に、視覚的にわかりやすい指定ができるのがミソ。

prettier-ignore しないと整形されてしまうのが難。prettier-ignore-start/end も最新版にあるらしいが VSCode の prettier プラグインだとプリインされてる prettier が古いのか有効化されなかった。

24
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
14