DimaLitvinenko / goit-react-hw-03-image-finder

Home Page:https://dimalitvinenko.github.io/goit-react-hw-03-image-finder/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

goit-react-hw-03-image-finder

Поиск изображений

Напиши приложение поиска изображений по ключевому слову.

Создай компоненты <Searchbar>, <ImageGallery>, <ImageGalleryItem>, <Loader>, <Button> и <Modal>. Готовые стили компонентов можно взять в файле styles.css и подправить под себя, если необходимо.

Инструкция Pixabay API

Для HTTP-запросов используй публичный сервис поиска изображений Pixabay. Зарегистрируйся и получи приватный ключ доступа.

URL-строка HTTP-запроса.

https://pixabay.com/api/?q=cat&page=1&key=your_key&image_type=photo&orientation=horizontal&per_page=12

Pixabay API поддерживает пагинацию, по умолчанию параметр page равен 1. Пусть в ответе приходит по 12 объектов, установлено в параметре per_page. Не забудь что при поиске по новому ключевому слову, необходимо сбрасывать значение page в 1.

В ответе от апи приходит массив объектов, в которых тебе интересны только следущие свойства.

  • id - уникальный идентификатор
  • webformatURL - ссылка на маленькое изображение для списка карточек
  • largeImageURL - ссылка на большое изображение для модального окна

Описание компонента <Searchbar>

Компонент принимает один проп onSubmit - функцию для передачи значения инпута при сабмите формы. Создает DOM-элемент следующей структуры.

<header class="searchbar">
   <form class="form">
      <button type="submit" class="button">
         <span class="button-label">Search</span>
      </button>

      <input
         class="input"
         type="text"
         autocomplete="off"
         autofocus
         placeholder="Search images and photos"
      />
   </form>
</header>

Описание компонента <ImageGallery>

Список карточек изображений. Создает DOM-элемент следующей структуры.

<ul class="gallery">
   <!-- Набор <li> с изображениями -->
</ul>

Описание компонента <ImageGalleryItem>

Компонент элемента списка с изображением. Создает DOM-элемент следующей структуры.

<li class="gallery-item">
   <img src="" alt="" />
</li>

Описание компонента <Button>

При нажатии на кнопку Load more должна догружаться следующая порция изображений и рендериться вместе с предыдущими. Кнопка должна рендерится только тогда, когда есть какие-то загруженные изобаржения. Если массив изображений пуст, кнопка не рендерится.

Описание компонента <Loader>

Компонент спинера, отображется пока идет загрузка изобаржений. Используй любой готовый компонент, например react-loader-spinner или любой другой.

Описание компонента <Modal>

При клике по элементу галереи должно открываться модальное окно с темным оверлеем и отображаться большая версия изображения. Модальное окно должно закрываться по нажатию клавиши ESC или по клику на оверлее.

Внешний вид похож на функционал этого VanillaJS-плагина, только вместо белого модального окна рендерится изображение (в примере нажми Run). Анимацию делать не нужно!

<div class="overlay">
   <div class="modal">
      <img src="" alt="" />
   </div>
</div>

React App.

Создает React приложение в текущей папке:

npx create-react-app .

Создает React приложение в папке my-app:

npx create-react-app my-app

Настройка pre-commit хуков

1 - Установка зависимостей

Установить в проект следующие пакеты.

npm i -D prettier eslint

В случае ошибки установить явно указать 7-ую версию: eslintv7.11.0 --->>

npm i -D prettier eslint@7.11.0

2 - Инициализация lint-staged и husky

Пользователям MacOS и Linux систем необходимо выполнить в терминале следующую команду. Она установит и настроит husky и lint-staged в зависимости от инструментов качества кода из зависимостей проекта в package.json.

npx mrm lint-staged

Пользователям Windows необходимо выполнить следующую команду. Она делает тоже самое:

npx mrm@2 lint-staged

3 - Установка дополнительных зависимостей (npm-пакетов):

-ESLint

eslint-config-react Набор самоуверенных правил ESLint (http://eslint.org) (включая все правила), адаптированных для проектов React.

npm i -S eslint-config-react babel-eslint eslint-plugin-react

eslint-config-react-app Этот пакет включает общую конфигурацию ESLint, используемую приложением Create React.

npm i -S eslint-config-react-app

-Prop-types

Проверка типа во время выполнения для свойств React и подобных объектов.

npm i -D prop-types

-Nano ID

Крошечный, безопасный, удобный для URL генератор уникальных строковых идентификаторов для JavaScript.

npm i -D nanoid

-Sass

Чтобы использовать Sass, установите node-sass:

npm i -S node-sass@6.0.0

-Postcss-loader

Инструмент для преобразования стилей с помощью плагинов JS и PostCSS-loader для webpack.

npm i -S postcss-loader postcss

-Modern-normalize

Сброс стилей.

npm i -S modern-normalize
import 'node_modules/modern-normalize/modern-normalize.css';

-React Icons

Включайте популярные значки в свои React проекты, используя импорт ES6, который позволяет вам включать только значки, которые использует ваш проект.

npm i -S react-icons
import { IconName } from 'react-icons/im';

-React Loader-Spinner

Спиннеры.

npm i -S react-loader-spinner
import Loader from 'react-loader-spinner';

-React Toastify

React-Toastify позволяет с легкостью добавлять уведомления в ваше приложение 🎉.

npm i -S react-toastify
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

-React Scroll

Компонент React для анимации вертикальной прокрутки.

npm i -S react-scroll

-React Scrollable Feed

Умная прокрутка интерфейсов и каналов чата.

npm i -S react-scrollable-feed

-AXIOS

HTTP-клиент на основе обещаний (Promise) для браузера и node.js.

npm i -S axios

4 - Добавить npm скрипты в файл package.json:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "deploy": "gh-pages -d build",
    "clean": "gh-pages-clean",
    "prepare": "husky install",
    "predeploy": "yarn build",
    ...
    "predeploy": "npm run build",
  },

5 - Интерграция плагинов

Ссылки на документацию по интеграции плагинов в популярные редакторы.

6 - Настройки VSCode

Для комфортной работы, после установки плагинов, нужно добавить несколько настроек редактора для автосохранения и форматирования файлов.

{
   "files.autoSave": "onFocusChange",
   "editor.formatOnSave": true,
   "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
   }
}

7 - Deployment на GitHub Pages

npm i -S gh-pages

package.json

"homepage": "https://имя-профиля.github.io/имя-репозитория",
"scripts": {
+   "predeploy": "npm run build",
+   "deploy": "gh-pages -d build",
    "start": "react-scripts start",
},

"homepage": "https://DimaLitvinenko.github.io/goit-react-hw-02-phonebook",

Getting Started with Create React App

This project was bootstrapped with Create React App.

Available Scripts

In the project directory, you can run:

npm start

Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser.

The page will reload if you make edits.
You will also see any lint errors in the console.

npm test

Launches the test runner in the interactive watch mode.
See the section about running tests for more information.

npm run build

Builds the app for production to the build folder.
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.
Your app is ready to be deployed!

See the section about deployment for more information.

npm run eject

Note: this is a one-way operation. Once you eject, you can’t go back!

If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

Learn More

You can learn more in the Create React App documentation.

To learn React, check out the React documentation.

Code Splitting

This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

Analyzing the Bundle Size

This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

Making a Progressive Web App

This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

Advanced Configuration

This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

Deployment

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment

npm run build fails to minify

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

About

https://dimalitvinenko.github.io/goit-react-hw-03-image-finder/

License:MIT License


Languages

Language:SCSS 47.6%Language:JavaScript 43.9%Language:HTML 8.2%Language:Shell 0.3%