reactjsscrolltop

how set Scroll to the top of the page after page change?


I have a problem, which I have no idea about. when the user changes the page the user stays at the bottom of the page. I want to take the user to the top of the page. I use to navigate by Id but it's not working. How can I solve this?

const handleSelect = (e) => {
        navigate('#manageItem')
        setLimit(e.target.value)

    }


    return (
        <div id='manageItem' div className='container mx-auto' >
            <PageTitle title={'Manage items-Laptop Stockroom'} />
            {isLoading ? <Spinner /> : <div className='grid grid-cols-1 gap-16 mt-16 md:grid-cols-3 p-4'>
                {
                    products.map(laptop => <SingleProduct
                        key={laptop._id}
                        laptop={laptop}
                    />
                    )
                }
            </div>}

            <div className='flex justify-center gap-2 my-12 items-center'>
                <div className='flex gap-2'>
                    {
                        [...Array(page).keys()].map(number => <>
                            <button
                                onClick={() => setActive(number)}
                                key={number}
                                className={`border-2 p-1 border-blue-500 font-semibold ${active === number ? 'bg-blue-500' : ''}`}
                            > {number + 1}</button>
                        </>)
                    }
                </div>
                <div>
                    <select onChange={handleSelect}>
                        <option value="6">6</option>
                        <option value="12">12</option>
                        <option value="18">18</option>
                    </select>
                </div>
            </div>
        </div >
    );
};

export default ManageItems;

Solution

  • you can do smth simple like

    const scrollToTop = () => {
      window.scrollTo(0, 0);
    }