Skip to content

Instantly share code, notes, and snippets.

@sorahn
Last active June 15, 2018 06:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sorahn/1a87bec26b006702d4fecd1f8942230b to your computer and use it in GitHub Desktop.
Save sorahn/1a87bec26b006702d4fecd1f8942230b to your computer and use it in GitHub Desktop.
playing with css grid and styled components.
import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
// Generate components for all of the areas in a grid template area.
export default class StyledGrid extends React.Component {
render() {
const { templateAreas } = this.props;
// Strip out the crap
// filter out dupes
// capitalize first letter
const temp = templateAreas
.replace(/\s+/g, " ")
.trim()
.split(" ")
.filter((t, i, f) => f.indexOf(t) === i)
.map(t => t[0].toUpperCase() + t.substr(1));
// Loop through all the names and make components for each one.
const components = temp.reduce(
(acc, cur, i) => ({
...acc,
[cur]: styled.div`
grid-area: ${cur.toLowerCase()};
`,
}),
{}
);
const Grid = styled.div`
display: grid;
grid-template-areas: ${this.props.templateAreas};
`;
return <Grid>{this.props.children(components)}</Grid>;
}
static propTypes = {
children: PropTypes.node,
};
}
//
// usage
//
const templateAreas = `
header header
sidebar content
footer footer
`;
const App = () => (
<StyledGrid templateAreas={templateAreas}>
{({ Header, Sidebar, Content, Footer }) => (
<React.Fragment>
<Header />
<Sidebar />
<Content />
<Footer />
</React.Fragment>
)}
</StyledGrid>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment