React.js Unsplash API Demo to Get Image By Pagination Using Axios in Javascript Complete Project

Welcome Learner today in this blog post we will be getting Images from Unsplash Api in react.js By pagination using Axios In js. All the Complete source code of the application is shown Down.

 

In order to lets started, you need to make a file index.html and copy-paste the mentioned code

index.html

<script>
var CONFIG = {
  __APP_ID__: '22b7b54287910389edfae878f576488bbc5b540a46daa0d2833ba858ce03b143',
  BASE_URL: 'https://api.unsplash.com/photos'
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<div id="mount-point"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>

 

style.css 

 

/*
* Prefixed by https://autoprefixer.github.io
* PostCSS: v7.0.29,
* Autoprefixer: v9.7.6
* Browsers: last 4 version
*/

* {
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
}

body {
  margin: 0;
  background-color: #f5f6f7;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  padding: 20px 0;
}

#mount-point {
  width: 100%;
}

.app {}

/* Галерея */
.grid {
  width: 100%;
  max-width: 1280px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
      -ms-flex-pack: justify;
          justify-content: space-between;
  -ms-flex-wrap: wrap;
      flex-wrap: wrap;
  margin: 0 auto;
  padding: 0;
  list-style-type: none;
}

.grid__item {
  margin: 0 10px 20px;
  -webkit-box-flex: 1;
      -ms-flex: 1 1 290px;
          flex: 1 1 290px;
}


/* Фотокарточки */
.card {
  background-color: #fff;
  overflow: hidden;
  -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
          box-shadow: 0 1px 2px rgba(0,0,0,.2);
  border-radius: 2px;
  line-height: 0;
  cursor: pointer;
}

.card:hover {
  -webkit-box-shadow: 0 3px 6px rgba(0,0,0,.2);
          box-shadow: 0 3px 6px rgba(0,0,0,.2)
}

.card__body {
  width: 100%;
  height: 215px;
  overflow: hidden;
  background-color: #eee;
}

.card__body img {
  width: 100%;
  height: 100%;
  -o-object-fit: cover;
     object-fit: cover;
}

.card__footer {
  width: 100%;
  padding: 10px 15px;
}

.media__obj {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #d8d8d8;
  margin-right: 15px;
  float: left;
}

.media__body {
  width: 100%;
  height: 32px;
  line-height: 32px;
}

.media__body a {
  font-family: Courier, serif;
  font-size: 15px;
  color: #999;
}

.media__body a:hover {
  text-decoration: none;
}


/* Пагинация */
.pagination {
  margin: 0 auto;
  max-width: 1280px;
  width: 100%;
  padding: 0 4px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
      flex-wrap: wrap;
  -webkit-box-pack: justify;
      -ms-flex-pack: justify;
          justify-content: space-between;
}

.pagination__left,
.pagination__right,
.pagination__mid {
  padding: 30px 0;
}

.pagination a,
.pagination span {
  display: block;
  text-align: center;
  font-family: Helvetica, Arial, sans-serif;
  font-weight: 300;
  line-height: 42px;
  height: 44px;
  color: #999;
  font-size: 18px;
}

.pagination a {
  padding: 0 16px;
  max-width: 160px;
  background-color: transparent;
  border-radius: 4px;
  border: 1px solid #ccc;
  text-decoration: none;
  margin: 0 6px;
  -webkit-transition: all .2s ease-in-out;
  -o-transition: all .2s ease-in-out;
  transition: all .2s ease-in-out;
}

.pagination a:hover,
.pagination a.current {
  border-color: #ea4c89;
  color: #ea4c89;
}

.pagination__mid {
  margin: 0 auto;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
}

.pagination__mid ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.pagination__mid li {
  display: inline-block;
}

.hidden {
  display: none !important;
}

.loader {
  position: fixed;
  z-index: 9;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
/*   position: relative; */
}

  .loader::before,
  .loader::after {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
  }

  .loader::before {
    background: hsla(0, 0%, 100%, 0.7);
  }

  .loader::after {
    content: '';
    font-size: 48px;
    width: 1em;
    height: 1em;
    border: 2px solid #ccc;
    border-top-color: #ea4c89;
    border-radius: 50%;
    -webkit-animation: spinner 1s linear infinite;
            animation: spinner 1s linear infinite;
  }

  @-webkit-keyframes spinner {
    to { -webkit-transform: rotate(1turn); transform: rotate(1turn); }
  }

  @keyframes spinner {
    to { -webkit-transform: rotate(1turn); transform: rotate(1turn); }
  }

 

 

script.js 

 

"use strict";

const {
  Component
} = React;
const {
  render
} = ReactDOM;
const LOAD_STATE = {
  SUCCESS: 'SUCCESS',
  ERROR: 'ERROR',
  LOADING: 'LOADING'
};

class App extends Component {
  constructor() {
    super();
    this.state = {
      photos: [],
      totalPhotos: 0,
      perPage: 5,
      currentPage: 1,
      loadState: LOAD_STATE.LOADING
    };
  }

  componentDidMount() {
    this.fetchPhotos(this.state.currentPage);
  }

  fetchPhotos(page) {
    var self = this;
    const {
      perPage
    } = this.state;
    const {
      appId,
      baseUrl
    } = this.props;
    const options = {
      params: {
        client_id: appId,
        page: page,
        per_page: perPage
      }
    };
    this.setState({
      loadState: LOAD_STATE.LOADING
    });
    axios.get(baseUrl, options).then(response => {
      self.setState({
        photos: response.data,
        totalPhotos: parseInt(response.headers['x-total']),
        currentPage: page,
        loadState: LOAD_STATE.SUCCESS
      });
    }).catch(() => {
      this.setState({
        loadState: LOAD_STATE.ERROR
      });
    });
  }

  render() {
    return /*#__PURE__*/React.createElement("div", {
      className: "app"
    }, /*#__PURE__*/React.createElement(Pagination, {
      current: this.state.currentPage,
      total: this.state.totalPhotos,
      perPage: this.state.perPage,
      onPageChanged: this.fetchPhotos.bind(this)
    }), this.state.loadState === LOAD_STATE.LOADING ? /*#__PURE__*/React.createElement("div", {
      className: "loader"
    }) : /*#__PURE__*/React.createElement(List, {
      data: this.state.photos
    }));
  }

}

const ListItem = ({
  photo
}) => {
  return /*#__PURE__*/React.createElement("div", {
    key: photo.id,
    className: "grid__item card"
  }, /*#__PURE__*/React.createElement("div", {
    className: "card__body"
  }, /*#__PURE__*/React.createElement("img", {
    src: photo.urls.small,
    alt: ""
  })), /*#__PURE__*/React.createElement("div", {
    className: "card__footer media"
  }, /*#__PURE__*/React.createElement("img", {
    src: photo.user.profile_image.small,
    alt: "",
    className: "media__obj"
  }), /*#__PURE__*/React.createElement("div", {
    className: "media__body"
  }, /*#__PURE__*/React.createElement("a", {
    href: photo.user.portfolio_url,
    target: "_blank"
  }, photo.user.name))));
};

const List = ({
  data
}) => {
  var items = data.map(photo => /*#__PURE__*/React.createElement(ListItem, {
    key: photo.id,
    photo: photo
  }));
  return /*#__PURE__*/React.createElement("div", {
    className: "grid"
  }, items);
};

class Pagination extends Component {
  pages() {
    var pages = [];

    for (var i = this.rangeStart(); i <= this.rangeEnd(); i++) {
      pages.push(i);
    }

    ;
    return pages;
  }

  rangeStart() {
    var start = this.props.current - this.props.pageRange;
    return start > 0 ? start : 1;
  }

  rangeEnd() {
    var end = this.props.current + this.props.pageRange;
    var totalPages = this.totalPages();
    return end < totalPages ? end : totalPages;
  }

  totalPages() {
    return Math.ceil(this.props.total / this.props.perPage);
  }

  nextPage() {
    return this.props.current + 1;
  }

  prevPage() {
    return this.props.current - 1;
  }

  hasFirst() {
    return this.rangeStart() !== 1;
  }

  hasLast() {
    return this.rangeEnd() < this.totalPages();
  }

  hasPrev() {
    return this.props.current > 1;
  }

  hasNext() {
    return this.props.current < this.totalPages();
  }

  changePage(page) {
    this.props.onPageChanged(page);
  }

  render() {
    return /*#__PURE__*/React.createElement("div", {
      className: "pagination"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pagination__left"
    }, /*#__PURE__*/React.createElement("a", {
      href: "#",
      className: !this.hasPrev() ? 'hidden' : '',
      onClick: e => this.changePage(this.prevPage())
    }, "Prev")), /*#__PURE__*/React.createElement("div", {
      className: "pagination__mid"
    }, /*#__PURE__*/React.createElement("ul", null, /*#__PURE__*/React.createElement("li", {
      className: !this.hasFirst() ? 'hidden' : ''
    }, /*#__PURE__*/React.createElement("a", {
      href: "#",
      onClick: e => this.changePage(1)
    }, "1")), /*#__PURE__*/React.createElement("li", {
      className: !this.hasFirst() ? 'hidden' : ''
    }, "..."), this.pages().map((page, index) => {
      return /*#__PURE__*/React.createElement("li", {
        key: index
      }, /*#__PURE__*/React.createElement("a", {
        href: "#",
        onClick: e => this.changePage(page),
        className: this.props.current == page ? 'current' : ''
      }, page));
    }), /*#__PURE__*/React.createElement("li", {
      className: !this.hasLast() ? 'hidden' : ''
    }, "..."), /*#__PURE__*/React.createElement("li", {
      className: !this.hasLast() ? 'hidden' : ''
    }, /*#__PURE__*/React.createElement("a", {
      href: "#",
      onClick: e => this.changePage(this.totalPages())
    }, this.totalPages())))), /*#__PURE__*/React.createElement("div", {
      className: "pagination__right"
    }, /*#__PURE__*/React.createElement("a", {
      href: "#",
      className: !this.hasNext() ? 'hidden' : '',
      onClick: e => this.changePage(this.nextPage())
    }, "Next")));
  }

}

;
Pagination.defaultProps = {
  pageRange: 2
};
render( /*#__PURE__*/React.createElement(App, {
  appId: CONFIG.__APP_ID__,
  baseUrl: CONFIG.BASE_URL
}), document.getElementById('mount-point'));

Leave a Comment

Your email address will not be published. Required fields are marked *