Only the displayed item freezes after reacting after the card

I am really surprised that this does not work, as I expected.

I want to show the username when a user visiting the site hangs over the user's message. Below is the code that I have. The problem is that when I hover over a message, every username in the array that I map appears. How can I change this so that it is only one username?

I think I need to change the state for each user message in a separate component, but I would not think that this should be necessary.

class App extends Component {

    state = {
        showUsername: false
    };

    showUsername = () => {

        this.setState({
            showUsername: true
        });

    }

    hideUsername = () => {

        this.setState({
            showUsername: false
        });

    }

    render() {

        let messageArr = this.props.messages.map(msg => {

            let name = `${msg.firstName} ${msg.lastName}`;

            return(
                <div key={msg.id}>

                    {this.state.showUsername && (
                        <span>{name}</span>
                    )}

                    <li><span onMouseEnter={this.showUsername} onMouseLeave{this.hideUsername}>{msg.message}</span></li>
                </div>
            );
        });

        return (
            <ul>
                {messageArr}
            </ul>
        );
    }
}
+4
source share
2 answers

I think I need to change the state for each user message in a separate component, but I would not think that this should be necessary.

Yes. It's necessary.

showUsername, , .

showUsername = (oneUserMessage) => {

    oneUserMessage.showUsername = true; // updating via reference
}

hideUsername = (oneUserMessage) => {

    oneUserMessage.showUsername = false;// updating via reference

}

//return in render

return (
            <div key={msg.id}>

                {msg.showUsername && (
                    <span>{name}</span>
                )}
                <li><span 
                  onMouseEnter={()=>{this.showUsername(msg)}} 
                  onMouseLeave={()=>{this.hideUsername(msg)}}>       
                  {msg.message}</span></li>


            </div>
        );
0

, this.state.showUsername - . , div, state true, this.state.showUsername true.

.

, div . , , divs .

, ​​:

        const messageArr = this.props.messages.map((msg) => <div key={msg.id}>
            <li>
               <span onMouseEnter={this.showUsername} onMouseLeave{this.hideUsername}>{msg.message}</span>
            </li>

        </div>);

return:)

0

Source: https://habr.com/ru/post/1685094/


All Articles