Junior — Senior
Rewrite and optimize React components
livecode
Task condition
Refactor the provided code to eliminate direct DOM manipulation and improve component structure.
App.tsx
import React, { useState, useEffect } from "react";
import "./styles.css";
import Item from "./Item";
export default function App() {
const [count, setCount] = useState(0);
const [isScrolled, setIsScrolled] = useState(false);
useEffect(() => {
const handleScroll = () => {
setIsScrolled(window.scrollY > 100);
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return (
<div className="App">
<div className="block-wrapper">
<div
className="top-section"
style={{
position: isScrolled ? "absolute" : "static",
top: isScrolled ? window.scrollY + "px" : undefined
}}
>
<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>
);
}