0

I want to change the state when scrolling. Here, the default value of the background is false. I want when scroll the page the value will be true and then I will change the className dynamically using the ternary operator. But it isn't working. please give me a solution using onScoll method and the background state will be changed when scroll the page.


const Header = () => {

    const [background, setBackground] = useState(false)




    return (
        <div onScroll={() => setBackground(true)} >
            <div >
   
                <div className={background ?
                 'nav bg-error w-[90%] py-5 mx-auto text-[white] flex justify-between ' 
                :
                 'nav w-[90%]  py-5 mx-auto text-[white] flex justify-between'}>
                    <div>
                        <p> logo</p>
                    </div>
                    <div>
                        <ul className='flex justify-around'>
                            <li>item1</li>
                            <li className='mx-10'>item2</li>
                            <li className='mr-10'>item3</li>
                            <li>item4</li>
                        </ul>
                    </div>
                </div>
                

            </div>
            <div className=' text-[white]'>
                <img src="https://img.freepik.com/free-photo/close-up-islamic-new-year-concept_23-2148611670.jpg?w=1380&t=st=1655822165~exp=1655822765~hmac=c5954765a3375adc1b56f2896de7ea8a604cd1fb725e53770c7ecd8a05821a60" alt="" />
            </div>
        </div>
    );
};

export default Header;

1 Answer 1

2

That's because you need to set overflow:scroll to the div. Otherwise the onScroll prop won't work.

But remember that using the solution above will render unwanted extra scrollbars. So you can try this instead:

  const [background, setBackground] = React.useState(false);

  React.useEffect(() => {
    window.addEventListener("scroll", (e) => setBackground(true));

    return () => {
      window.removeEventListener("scroll", (e) => setBackground(false));
    };
  }, [background]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.