7 views
In the React example, the counter updates when the button is clicked. Make the value reappear with the original fade animation on every update, using only React, without CSS animations or vanilla JavaScript.
Asked at
AI answer
To trigger the appearance again, you can remount the element with a new key. For example, give it an initial opacity and change it after mounting. The example below uses a CSS transition rather than a CSS animation; React manages the state and retriggering.
import { useEffect, useState } from "react";
function FadeValue({ value }) {
const [visible, setVisible] = useState(false);
useEffect(() => {
setVisible(true);
}, []);
return (
<span
style={{
opacity: visible ? 1 : 0,
transition: "opacity 400ms ease",
}}
>
{value}
</span>
);
}
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<FadeValue key={count} value={count} />
<button onClick={() => setCount((current) => current + 1)}>
Increase
</button>
</>
);
}
Each time count changes, the key changes, React creates a new FadeValue, and the transition starts again. If the restriction also rules out CSS transitions, React alone is not enough: React updates the interface but does not perform visual interpolation on its own.
Also asked at ООО «Софтнетикс» (Softnetix)
- Tell us about yourself, your experience, and your recent projects.
- What is memoization in React and how do useMemo, useCallback, and React.memo work?
- Tell me about XSS attacks: types and protection methods.
- What static methods of Promise do you know? Tell about them.
- Why is using array index as a key an anti-pattern in React?
Similar questions
- Describe what happens when you press a button in a React component with a counter: how useState works, how React understands which part of the DOM to update?
- Practical task: improve the React counter component so that when clicking the 'Increase' button, the counter value increases by 1 and a record of the increase with the new value is added to the history; when clicking 'Decrease' — similarly; when clicking 'Reset' — the history is cleared.
- There is a React component with a counter (useState), a button that increments the counter by 1, and a list of 100 items. What happens when the button is clicked?
- There is a vanilla JavaScript application and a React application: both have a paragraph and a button that changes the paragraph text on click. Where will the change happen faster and what will be more optimal?
- Write a React component with an Add button. When clicked, a new button with a sequential number is added. When the created button is clicked, it is removed. The removal should work correctly (not by index, but by a unique identifier).