React - Conditionally change the style of an element based on its own position

Viewed 23

I'm trying to change the opacity of an element based on its own position (show it only if its bigger than 500px):

export const Card = ({ pic }) => {
    const card = useRef(null);
    return (
        <li
            ref={card}
            style={{opacity: 500 > card.current.getBoundingClientRect().y ? 1 : 0}}
        >
            <img src={pic} />
        </li>
    );
};

But I got this error: Uncaught TypeError: Cannot read properties of null (reading 'getBoundingClientRect')

And could not figure out how to access its position currectly.

Thanks!

1 Answers

You shouldn’t read the current value during rendering, as said in the documentation

During the first render, the DOM nodes have not yet been created, so ref.current will be null. And during the rendering of updates, the DOM nodes haven’t been updated yet. So it’s too early to read them.

You could use state instead

const Card = ({pic}) => {
    const card = useRef(null);
    const [y, setY] = useState(0)

    useEffect(() => {
        setY(card.current.getBoundingClientRect().y)
    }, [])

    return (
        <li
            ref={card}
            style={{opacity: 500 > y ? 1 : 0}}
        >
            <img src={pic} />
        </li>
    );
};
Related