Назад к задачам
Junior — Senior
59

Переписать и оптимизировать React‑компоненты

Компании, где спрашивали:

Pari
Получайте помощь с лайвкодингом в реальном времени с Sobes Copilot
Условие задачи

Выполнить рефакторинг представленного кода, устранив прямое взаимодействие с DOM и улучшив структуру компонентов.

App.tsx

import React, { useState } from "react";
import "./styles.css";
import Item from "./Item";

export default function App() {
  const [count, setCount] = useState(0);
  window.addEventListener("scroll", () => {
    const { scrollY } = window;
    if (scrollY > 100) {
      const topSection = document.querySelector<HTMLDivElement>(".top-section");
      if (topSection) {
        topSection.style.position = "absolute";
        topSection.style.top = scrollY + "px";
      } else {
        return;
      }
    } else {
      const topSection = document.querySelector<HTMLDivElement>(".top-section");
      if (topSection) {
        topSection.style.position = "static";
      } else {
        return;
      }
    }
  });

  return (
    <div className="App">
      <div className="block-wrapper">
        <div className="top-section">
          <button
            onClick={() => {
              alert(count);
            }}
          >
            Show count
          </button>
          <button
            onClick={() => {
              setCount(0);
            }}
          >
            Reset count
          </button>
        </div>
        <Item
          onAdd={() => {
            setCount(count + 1);
          }}
        />
        <Item
          onAdd={() => {
            setCount(count + 1);
          }}
        />
        <Item
          onAdd={() => {
            setCount(count + 1);
          }}
        />
        <Item
          onAdd={() => {
            setCount(count + 1);
          }}
        />
        <Item
          onAdd={() => {
            setCount(count + 1);
          }}
        />
        <Item
          onAdd={() => {
            setCount(count + 1);
          }}
        />
      </div>
    </div>
  );
}

Item.tsx

import React from "react";
import "./styles.css";

type Props = {
  onAdd: () => void;
};

export default function Item(props: Props) {
  return (
    <div className="block">
      <button className="btn" onClick={props.onAdd}>
        Add to cart
      </button>
    </div>
  );
}