To ensure that the last item of the loop is always visible in the middle of the screen after a search, you can use a combination of React's useRef and useEffect hooks along with DOM manipulation. Here's how you can modify your code to achieve this:
- Add a ref to the last item in your loop.
- Use useEffect to scroll the last item into view after each search.
Here's an example of how you can modify your code:
// useState hook
const PageMain = () => {
const [lastItemRef, setLastItemRef] = useState(null);
// Effect to scroll the last item into view after each search
useEffect(() => {
if (lastItemRef) {
lastItemRef.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [lastItemRef]);
// in JSX
{resultList.map((question, index) => (
<div
key={index}
ref={index === resultList.length - 1 ? setLastItemRef : null}
>