JavaScript for WordPress Forums Bugs & Issues Using React on Frontend Lightbox Error

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #151006
    cvwlc
    Participant

    Getting console error: “Cannot read property ‘0’ of undefined” after adding front-end lightbox code in Adv WP Block Dev course and consequently Lightbox is not working… here is my code… Have I made an error or is this a bug/code change since the tutorial?

    FrontendGallery.js:

    import Gallery from "react-photo-gallery";
    import Lightbox from "react-images";
    
    export default class FrontendGallery extends React.Component {
      state = {
        currentImage: 0
      };
      openLightbox = (event, obj) => {
        this.setState({
          currentImage: obj.index,
          lightboxIsOpen: true
        });
      };
      closeLightbox = () => {
        this.setState({
          currentImage: 0,
          lightboxIsOpen: false
        });
      };
      gotoPrevious = () => {
        this.setState({
          currentImage: this.state.currentImage - 1
        });
      };
      gotoNext = () => {
        this.setState({
          currentImage: this.state.currentImage + 1
        });
      };
      render() {
        return (
          <div>
            <Gallery
              photos={this.props.photos}
              direction={this.props.direction}
              onClick={this.openLightbox}
            />
            {this.props.islightboxenabled == "true" && (
              <Lightbox
                images={this.props.photos}
                onClose={this.closeLightbox}
                onClickPrev={this.gotoPrevious}
                onClickNext={this.gotoNext}
                currentImage={this.state.currentImage}
                isOpen={this.state.lightboxIsOpen}
              />
            )}
          </div>
        );
      }
    }

    frontend.js:

    const { render } = wp.element;
    
    import FrontendGallery from "./components/FrontendGallery";
    
    const galleries = document.querySelectorAll(
      ".wp-block-jsforwpadvblocks-gallery"
    );
    
    galleries.forEach( gallery => {
      const direction = gallery.dataset.direction;
      const islightboxenabled = gallery.dataset.islightboxenabled;
      const images = gallery.querySelectorAll("img");
    
      const photos = [];
      images.forEach(img => {
        photos.push({
          src: img.src,
          width: img.width,
          height: img.height,
          alt: img.alt,
          caption: img.caption
        });
      });
      render(
        <FrontendGallery
          photos={photos}
          direction={direction}
          islightboxenabled={islightboxenabled}
        />,
        gallery
      );
    });

    And index.js:

    /* gather block dependencies*/
    import icon from './icon';
    import './style.scss';
    import Gallery from 'react-photo-gallery';
    //import { MediaPlaceholder } from '@wordpress/block-editor';
    
    /* block librarires*/
    const { __ } = wp.i18n;
    const { Fragment } = wp.element;
    const { registerBlockType } = wp.blocks;
    const { BlockControls, InspectorControls, MediaUpload, MediaPlaceholder } = wp.blockEditor;
    const { IconButton, Toolbar, PanelBody, PanelRow, RadioControl } = wp.components;
    /*register block*/
    
    export default registerBlockType("jsforwpadvblocks/gallery", {
      title: __("Gallery", "jsforwpadvblocks"),
      description: __("A demo custom gallery block", "jsforwpadvblocks"),
      category: "jsforwpadvblocks",
      icon,
      keywords: [
        __("Masonry","jsforwpadvblocks"),
        __("Images Media","jsforwpadvblocks"),
        __("Lightbox","jsforwpadvblocks")
      ],
      supports:[ "full", "wide"],
      attributes: {
        images: {
          type: "array",
          default: []
        },
        direction: {
          type: "string",
          default: "row"
        },
        islightboxenabled: {
          type: "boolean",
          default: true
        }
      },
      edit: props => {
        const {
          attributes : {images, direction, islightboxenabled},
          className,
          setAttributes
        } = props;
        const onSelectImages = newImages => {
          //console.log(newImages);
            const images = newImages.map( img => {
              return {
                src: img.sizes.large.url,
                width: img.sizes.large.width,
                height: img.sizes.large.height,
                id: img.id,
                alt: img.alt,
                caption: img.caption
              };
            });
            setAttributes({ images, direction });
        };
        return (
          <Fragment>
          <InspectorControls>
            <PanelBody title={__("Gallery Settings", "jsforwpadvblocks")} initialOpen={true}>
              <PanelRow>
                <RadioControl
                  label={__("Grid Style", "jsforwpadvblocks")}
                  selected={direction}
                  options={[
                    {label: __("Rows", "jsforwpadvblocks"), value: "row"},
                    {label: __("Columns", "jsforwpadvblocks"), value: "column"}
                  ]}
                  onChange={direction => setAttributes({direction, islightboxenabled})}
                />
              </PanelRow>
            </PanelBody>
          </InspectorControls>
          {!!images.length && (
            <BlockControls>
              <Toolbar>
                <MediaUpload
                  allowedTypes={["images"]}
                  multiple
                  gallery
                  value={images.map(img => img.id)}
                  onSelect={onSelectImages}
                  render={({open}) =>(
                    <IconButton
                      className="components_toolbar__control"
                      label={__("Edit Gallery", "jsforwpadvblocks")}
                      icon="edit"
                      onClick={open}
                    />
                  )}
                />
              </Toolbar>
            </BlockControls>
          )}
    
          <div className = {<code>${className}${direction}</code>}>
          {!!!images.length ?
            (
              <MediaPlaceholder
                labels = {{
                  title: __("Gallery", "jsforwpadvblocks"),
                  instructions: __("Drag images, upload new ones or select files from your library.", "jsforwpadvblocks")
                }}
                icon = {icon}
                accept ="images/*"
                multiple
                onSelect = {onSelectImages}
              />
            ) :
            (
              <Gallery photos={ images } direction={direction} />
            )
          }
    
          </div>
          </Fragment>
        );
      },
      save: props => {
        const { images, direction, islightboxenabled } = props.attributes;
    
        return (
          <div className={<code>${direction}</code>} data-direction={direction} data-islightboxenabled={islightboxenabled} >
            {images.map(img => (<img src={img.src} width={img.width} height={img.height} data-id={img.id} data-caption={img.caption} alt={img.alt} />))}
          </div>
        );
      }
    
    })
    

    Thanks for help – stuck here since the error isn’t very informative.

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.