M
M
Merrii2018-09-28 11:03:14
JavaScript
Merrii, 2018-09-28 11:03:14

How to split a React.js component?

I'm doing my first learning project in react - a simple site with a gallery. There is a component that displays a gallery. I want to properly divide it, at least highlight it . Tell me how to highlight it so that it works?<Item />

import React from "react";
import PropTypes from "prop-types";

function imagesLoaded(parentNode) {
  const imgElements = [...parentNode.querySelectorAll("img")];
  for (let i = 0; i < imgElements.length; i += 1) {
    const img = imgElements[i];
    if (!img.complete) {
      return false;
    }
  }
  return true;
}

export class Gallery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true
    };
  }

  handleImageChange = () => {
    this.setState({
      loading: !imagesLoaded(this.galleryElement)
    });
  };

  renderSpinner() {
    if (!this.state.loading) {
      return null;
    }
    return <span className="spinner" />;
  }


  render() {
    return (
      <div className="gallery container"
        ref={element => {
          this.galleryElement = element;
        }}
      >
        {this.renderSpinner()}
        <div className="images row">
          {this.props.imageUrls.map(imageUrl=>
            <div key={imageUrl.toString()}
            className="col-md-4 image-item backgrounded"
             onLoad={this.handleImageChange}
            onError={this.handleImageChange}
             style ={ { backgroundImage: "url("+imageUrl+")" } }>             
            </div>
          )}
        </div>
      </div>
    );
  }
}
Gallery.propTypes = {
  imageUrls: PropTypes.arrayOf(PropTypes.string).isRequired
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mr jeery, 2018-09-29
@Merrii

{this.props.imageUrls.map(imageUrl=>
            <div key={imageUrl.toString()}
            className="col-md-4 image-item backgrounded"
             onLoad={this.handleImageChange}
            onError={this.handleImageChange}
             style ={ { backgroundImage: "url("+imageUrl+")" } }>             
            </div>
          )}

Here you iterate over the ImageUrls array and create a div for each of its elements where you put the value of the element.
Respectively
<div key={imageUrl.toString()}
            className="col-md-4 image-item backgrounded"
             onLoad={this.handleImageChange}
            onError={this.handleImageChange}
             style ={ { backgroundImage: "url("+imageUrl+")" } }>

Can be replaced with
<Image key={imageUrl.toString()}
             onLoad={this.handleImageChange}
            onError={this.handleImageChange}
             style ={ { backgroundImage: "url("+imageUrl+")" } }>

By creating the Image class

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question