0

I have done an npm install on masonry-layout -- but when I render this component it comes up with an element undefined error? "Cannot set property 'element' of undefined"

here is a jsfiddle

http://jsfiddle.net/0ht35rpb/82/

I am new to reactjs and I am trying to get the masonry layout grid to work. https://masonry.desandro.com/#package-managers

import React from 'react'
// import $ from 'jquery'

import Masonry from 'masonry-layout'

class VideoGrid extends React.Component {
  componentDidMount () {
    this.invokeMasonry()
  }

  invokeMasonry () {
    var elem = document.querySelector('.grid')
    Masonry(elem, {
      itemSelector: '.grid-item',
      columnWidth: '.grid-sizer',
      percentPosition: true
    })
  }

  render () {
    return (
      <div className='grid'>
        <div className='grid-sizer width2' />
        <div className='grid-item width2'>
          <img src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/orange-tree.jpg' />
        </div>
        <div className='grid-item width2'>
          <img src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/submerged.jpg' />
        </div>
      </div>
    )
  }
}

export default VideoGrid
The Old County
  • 89
  • 13
  • 59
  • 129

1 Answers1

1

as per documentation,

var elem = document.querySelector('.grid')
    Masonry(elem, {
      itemSelector: '.grid-item',
      columnWidth: '.grid-sizer',
      percentPosition: true
    })

Should be:

 var elem = document.querySelector('.grid')
var msnry = new Masonry( elem, {
          itemSelector: '.grid-item',
          columnWidth: '.grid-sizer',
          percentPosition: true
});
Ved
  • 11,837
  • 5
  • 42
  • 60
  • no - my reactjs project declines the use of "new" tag - also it will flare up an error because msnry is not used -- this isn't the problem - its as if elem is undefined when it gets invoked – The Old County Jun 29 '17 at 05:22
  • elem should not be undefined as you are invoking selector on `componentDidMount `. – Ved Jun 29 '17 at 05:25
  • If you console.log(elem), do you get the elem ? – Ved Jun 29 '17 at 05:26
  • -- yes -- but still "Uncaught TypeError: Cannot set property 'element' of undefined" – The Old County Jun 29 '17 at 05:53
  • I added the new -- tag and that seems to have solved it -- but then masonry renders maybe too soon - and so the elements stack -- and only toggling the width they sort themselves out properly – The Old County Jun 29 '17 at 09:27
  • It is - but the masonry kicks in and just stacks the items up -- maybe its because the blocks don't have height initially – The Old County Jun 29 '17 at 09:35
  • adding height seems to fix that - but then locks it down -- mm should I reload it after render? – The Old County Jun 29 '17 at 09:37
  • Can't say. need to check that. Anyway your actual issue resolved. Mark answer as selected if it helped in solving. – Ved Jun 29 '17 at 09:39