-
-
Save sorahn/1a87bec26b006702d4fecd1f8942230b to your computer and use it in GitHub Desktop.
playing with css grid and styled components.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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