Why is this app code only working from the right side or else the ReactDOM.findDOMNode querySelector cant find className

Viewed 63

I learn Reactjs and Javascript and have a questions regarding this small one file
Codesandbox Hover effect REACT (forked).
The app is sliding in an overlay with text when mouse moves over it and the overlay hides when mouse leave.

Why is it only often working when mouse enter and exist from the right side? Try it you'll see kind of strange..

I see this error:

enter image description here

I check in the DOM and there is a correct className I think so maybe it's I'm using some mix of wrong version imports or it's a timing issue?

I made a movie clips

1 Answers

When handleMouseLeave, event target will be children component like( p, h2, h3,...). So, ReactDOM.findDOMNode(e.target).querySelector can not find outer like .box-content.

I suggest simple solution use useState.

import React from "react";
import axios from "axios";

class App extends React.Component {
    state = {
        posts: [],
        hoverIndex: null,
    };

    componentDidMount() {
        axios
            .get(`https://jsonplaceholder.typicode.com/posts`)
            .then((res) => {
                this.setState({ posts: res.data });
            })
            .then((error) => {
                console.log(error);
            });
    }

    handleMouseEnter = (e) => {
        if (e.target.id !== null) {
            this.setState({hoverIndex: e.target.id});
        }
    };

    handleMouseLeave = (e) => {
        this.setState({hoverIndex: null});
    };

    render() {
        const { posts } = this.state;

        return (
            <div>
                {posts.map((e, index) => (
                    <div
                        onMouseEnter={this.handleMouseEnter}
                        onMouseLeave={this.handleMouseLeave}
                        className={"box-container"}
                        id={index}
                        key={e.id}
                    >
                        <h3>HOVER ME</h3>
                        <div
                            className={"box-content " + (this.state.hoverIndex === index.toString() ? 'hovered' : "")}
                        >
                            <h2>{e.title}</h2>
                            <p>{e.body}</p>
                        </div>
                    </div>
                ))}
            </div>
        );
    }
}

export default App;
Related