Guilherme Moreira
Guilherme Moreira

Reputation: 23

My state changes, but does not add class when useEffect, when I scroll

I need to change the background of a JSX element when the page goes down by 320 px, all with useEffect and useState. So far I managed to change the state, but does not add background class of another color.

I am using NODE 8.9.3, NPM 5.5.1 and REACT JS 16.9.0

import React, { useEffect, useState } from 'react'

import { useScrollYPosition } from 'react-use-scroll-position'

import { Container } from '../../styles/Container'
import { ContainerCustom, HeaderComp } from './styles'

import Logo from './Logo'
import Menu from './Menu'
import Icons from './Icons'

const ContainerBox = () => {
  return (
    <ContainerCustom fluid>
      <Container>
        <HeaderComp>
          <Logo />
          <Menu />
          <Icons />
        </HeaderComp>
      </Container>
    </ContainerCustom>
  )
}

const Header = () => {
  const [back, setBack] = useState(0)

  const handleBackState = () => {
    const scrollY = window.scrollY
    if (scrollY > 320) {
      setBack(1)
      console.log(`Estado: ${back}`)
    } else {
      setBack(0)
      console.log(`Estado após remover: ${back}`)
    }
  }

  useEffect(() => {
    window.addEventListener('scroll', handleBackState)
    return () => {
      window.removeEventListener('scroll', handleBackState)
    }
  }, [handleBackState])
  return <ContainerBox className={back === 1 ? 'removeGradients' : ''} />
}

On console has the output State: 0, and after 320, State after remove: 1

Upvotes: 2

Views: 872

Answers (1)

trixn
trixn

Reputation: 16309

Not every component also has a representation in the DOM. You need to apply the className to a component that actually has a corresponding DOM element to have your styles take any effect:

// className will not affect the DOM as this component does not render a DOM element
const WrappingComponent = ({className}) => (
    <WrappedComponent className={className} />
);

// this className will be applied to the div in the DOM
const WrappedComponent = ({className}) => (
    <div className={className}>Content here</div>
);

Upvotes: 1

Related Questions