2

I'm using Next js and react visibility sensor to let me know when a div is visible on screen.

Code kinda looks like:

import VisibilitySensor from "react-visibility-sensor";


function onChange(isVisible) {
  let colorstate = isVisible ? "test" : "test dark";
  console.log(colorstate)
}

export default function Home() {
  return (
              <VisibilitySensor onChange={onChange}>

                <div className={colorstate}>this is a test div.</div>

              </VisibilitySensor>
);
}

Changing the div className to the {colorstate} variable doesn't work (returns undefined).

I'm fairly new to React and I tried various answers online using "this.state" methods which all didn't work.

Right now the onChange function works fine and prints the correct class name in the log, I just don't know how to associate it with the div.

Thanks.

2 Answers 2

2

You can use useState hook, this is how it would look like with initial className of 'test dark'

import VisibilitySensor from "react-visibility-sensor";
import {useState} from 'react'

export default function Home() {
const [colorState, setColorState] = useState('test dark')

const onChange = (isVisible) => {
  isVisible ? setColorState("test") : setColorState("test dark");
}

  return (
              <VisibilitySensor onChange={onChange}>

                <div className={colorState}>this is a test div.</div>

              </VisibilitySensor>
);
}
Sign up to request clarification or add additional context in comments.

Comments

2

seems your colorState variable is visible only through the onChange.

class Home extends React.Component{

    constructor(props){
        super(props);
        this.state = 
        {
            dark: true
        }
        
    }

    test = () => {
        this.setState(
            {
                dark: !this.state.dark
            }
        )
    }

    render(){
        return(
        <div className={this.state.dark ? "dark" : "white"} onClick={this.test}>
            test
        </div>
        );
    }
}

should work

2 Comments

Thanks for the answer! This is unfortunately not working (also changed the console.log to the new variable state). If I set the initial state as either light or dark, that gets passed to the div. However when the onChange function is run, the only thing that happens is the console logs the new state, but it doesn't get transferred to the className of the div :(
this style will work if you define your component as an ECMA6 class. updated the answer

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.