⚛️ React parallax

⚛️ React parallax


Parallax.jsx

Данный код представляет компонент React под названием Parallax, который создает веб-страницу с эффектом параболической прокрутки (parallax scrolling).

import "./styles.css";

import html from "./html.png";
import css from "./css.png";
import es6 from "./es6.png";
import react from "./react.png";

import gsap from "gsap";
import { ScrollTrigger } from "gsap/all";

import logo from "./logo.svg";
import { useEffect, useRef } from "react";

export const Parallax = () => {
    const containerRef = useRef();

    useEffect(() => {
        gsap.registerPlugin(ScrollTrigger);
        const sections = gsap.utils.toArray(".panel");
        gsap.to(sections, {
            xPercent: -100 * (sections.length - 1),
            ease: "none",
            scrollTrigger: {
                trigger: ".container",
                pin: true,
                scrub: 1,
                snap: 1 / (sections.length - 1),
                end: () => "+=" + containerRef.current.offsetWidth,
            },
        });
    }, []);

    return (
        <>
            <nav>
                <img src={logo} />
                <a href="#"> Home </a>
                <a href="#"> Skills </a>
                <a href="#"> Contact </a>
            </nav>
            <section className="banner">
                <div className="banner-content">
                    <h2>Hi, I'm Peter</h2>
                    <h3>Frontend Developer</h3>
                </div>
            </section>
            <div ref={containerRef} className="container">
                <section className="description panel blue">
                    <img src={html} />
                    <h2>HTML</h2>
                    <p>
                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Animi
                        labore eius cum perferendis consectetur culpa laboriosam quam, sed
                        ea nihil, suscipit, quidem est expedita. Nihil enim obcaecati
                        deleniti eaque sed.
                    </p>
                </section>
                <section className="panel red">
                    <img src={css} />
                    <h2>CSS</h2>
                    <p>
                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Animi
                        labore eius cum perferendis consectetur culpa laboriosam quam, sed
                        ea nihil, suscipit, quidem est expedita. Nihil enim obcaecati
                        deleniti eaque sed.
                    </p>
                </section>
                <section className="description panel blue">
                    <img src={es6} />
                    <h2>ES6</h2>
                    <p>
                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Animi
                        labore eius cum perferendis consectetur culpa laboriosam quam, sed
                        ea nihil, suscipit, quidem est expedita. Nihil enim obcaecati
                        deleniti eaque sed.
                    </p>
                </section>
                <section className="panel red">
                    <img src={react} />
                    <h2>React JS</h2>
                    <p>
                        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Animi
                        labore eius cum perferendis consectetur culpa laboriosam quam, sed
                        ea nihil, suscipit, quidem est expedita. Nihil enim obcaecati
                        deleniti eaque sed.
                    </p>
                </section>
            </div>
            <section className="footer">
                <h2>Contact</h2>
                <form>
                    <input type="text" placeholder="Your email" />

                    <textarea rows={6} placeholder="Message" />
                    <button>SUBMIT</button>
                </form>
            </section>
        </>
    );
};

Импортируются необходимые модули gsap и ScrollTrigger из библиотеки GSAP (GreenSock Animation Platform). GSAP используется для создания анимаций, а ScrollTrigger - для управления анимациями при прокрутке страницы.

Затем компонент Parallax определяет референс containerRef, который будет использоваться для обращения к контейнеру с разделами (sections) на странице. Используется хук useEffect, который выполняет код после рендеринга компонента.

Внутри хука useEffect вызывается gsap.registerPlugin(ScrollTrigger), чтобы зарегистрировать плагин ScrollTrigger. Затем используется метод gsap.utils.toArray(".panel"), чтобы получить массив разделов (sections) с классом .panel. Затем применяется анимация gsap.to(), которая перемещает разделы по горизонтальной оси с помощью свойства xPercent и управляется с помощью ScrollTrigger.

Возвращаемый компонент Parallax содержит разметку страницы, которая включает в себя навигационную панель (<nav>), баннер (<section className="banner">), контейнер с разделами (<div ref={containerRef} className="container">) и подвал (<section className="footer">).

Каждый раздел представлен внутри элемента <section> с определенным классом (blue или red). Внутри раздела есть изображение, заголовок и абзац с текстом.

Style.css

html {
  overflow-y: scroll;
  height: 100%;
  -webkit-overflow-scrolling: touch;
  overflow-scrolling: touch;
}

* {
  box-sizing: border-box;
}

body {
  overflow-y: visible;
  position: relative;
  height: unset;
  font-family: "Euclid Circular A", "Poppins";
  color: #222222;
  text-align: center;
}
html,
body {
  overflow-x: hidden;
  margin: 0;
}

.container {
  width: 400%;
  height: 100vh;
  display: flex;
  flex-wrap: nowrap;
  background: #f7f7f7;
}

img {
  width: 170px;
  height: 170px;
  object-fit: contain;
}

.banner h2,
.footer h2 {
  margin: 20px 0;
}

nav {
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  display: flex;
  gap: 20px;
  align-items: center;
  padding: 0 24px 0 16px;
  background: #ffffff;
  box-shadow: 0 0 20px rgb(0 0 0 / 8%);
}

nav a {
  text-decoration: none;
  color: inherit;
  font-size: 14px;
  font-weight: 600;
}

nav img {
  width: 32px;
  height: 32px;
}

section {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  padding: 0 80px;
}

h2 {
  margin: 50px 0 20px;
}

p {
  opacity: 0.66;
  font-size: 16px;
}

.banner {
  flex-direction: row;
  text-align: left;
  gap: 30px;
  background: url("./bg.jpeg");
  background-size: cover;
  background-position: center;
  color: #f7f7f7;
}

.banner-content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(rgb(57 53 86 / 0%), rgb(57 53 86 / 100%) 90%);
}

.banner h2 {
  font-size: 40px;
}

.banner h3 {
  margin: 0;
  opacity: 0.7;
}

.footer {
  background: #ffffff;
}

.panel {
  width: 100%;
  height: 100%;
}

.container .panel:nth-child(odd) {
  background: #f1f0f7;
}

form {
  padding: 0;
  margin: 0;
  display: grid;
  gap: 10px;
  padding-top: 20px;
}

input,
textarea,
button {
  font-family: inherit;
  border-radius: 6px;
  border: 0;
  background: #f1f0f7;
  padding: 16px;
  width: 340px;
  font-size: 16px;
}

button {
  background: #7b66fd;
  color: #f7f7f7;
  font-weight: 600;
  letter-spacing: 2px;
}


Report Page