Skip to content

Instantly share code, notes, and snippets.

@adeleke5140
Last active March 18, 2023 18:02
Show Gist options
  • Select an option

  • Save adeleke5140/8a4f1ba06c274e266ea14e9f2a868e3f to your computer and use it in GitHub Desktop.

Select an option

Save adeleke5140/8a4f1ba06c274e266ea14e9f2a868e3f to your computer and use it in GitHub Desktop.
Build a modular and extensible Grid with ReactJS

Introduction

The key to building a responsive grid is by using the range utility function. It works by returning the amount of element for a given number range, excluding the end.

For example, if you wanted to create 5 elements, you call range(5). Additional parameters include, the start, end and step argument.

Live Sandbox link

import Grid from './Grid'
function App(){
return (
<Grid numRows={2} numCols={4}/>
)
}
export default App
import { range } from './utils'
const Grid = ({ numRows, numCols}) => {
return(
<div className="grid">
{range(numRows).map(row => (
<div className="row" key={row}>
{range(numCols).map(col => (
<div className="cell" key={col}></div>
))}
</div>
))}
</div>
)
}
export default Grid
:root{
--spacing: 8px;
}
.grid{
display: flex;
flex-direction: column;
gap: var(--spacing);
padding: var(--spacing);
background: white;
border-radius: 8px;
max-width: 500px;
margin: 0 auto;
}
.row {
display: flex;
gap: var(--spacing)
}
.cell{
flex: 1;
aspect-ratio: 1/1;
border: 1px solid hsl(210deg 20% 80%);
border-radius: 4px;
}
const range= (start, end, step=1) => {
const output = []
if(typeof end === "undefined"){
end = start;
start = 0
}
for(let i = start; i < end; i++){
output.push(i)
}
return output
}
export { range }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment