Skip to content
This repository has been archived by the owner on Apr 4, 2023. It is now read-only.

Commit

Permalink
Fix column count when rerender
Browse files Browse the repository at this point in the history
  • Loading branch information
mustofa-id committed Jul 2, 2019
1 parent 71bb264 commit d4912fc
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions src/components/widget/masonry.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,35 @@ import React, { useState, useEffect } from 'react'
const Masonry = ({ column, children, breakpoint }) => {
if (!children) return null

const [columnCount, setColumnCount] = useState(breakpoint.default)
const [columnCount, setColumnCount] = useState(getColumnCount())

useEffect(() => {
calculateColumnCount()
if (window) window.addEventListener('resize', calculateColumnCount)
return () => {
if (window) {
window.removeEventListener('resize', calculateColumnCount)
}
if (window) {
updateColumn()
window.addEventListener('resize', updateColumn)
return () => window.removeEventListener('resize', updateColumn)
}
})

function calculateColumnCount () {
function getColumnCount () {
const width = (window && window.innerWidth) || Infinity

let matchedBreakpoint = Infinity
let columns = breakpoint.default

for (let bp in breakpoint) {
const optBreakpoint = parseInt(bp)
const isCurrentBreakpoint = optBreakpoint > 0 && width <= optBreakpoint

if (isCurrentBreakpoint && optBreakpoint < matchedBreakpoint) {
matchedBreakpoint = optBreakpoint
columns = breakpoint[bp]
}
}
return Math.max(1, parseInt(columns) || 1)
}

columns = Math.max(1, parseInt(columns) || 1)

if (columnCount !== columns) {
setColumnCount(columns)
function updateColumn () {
const mColumnCount = getColumnCount()
if (columnCount !== mColumnCount) {
setColumnCount(mColumnCount)
}
}

Expand Down

0 comments on commit d4912fc

Please sign in to comment.