A
A
Alexander Ivanov2018-02-09 23:33:50
React
Alexander Ivanov, 2018-02-09 23:33:50

How to handle events in map React?

There are similar questions but no answers.

handlePopup=(e)=>{
        alert(123)
    };
    render(){
        return(
            <div className="posts">
                {this.props.articles.map(function(article){
                    return <div key={article.pid} className="posts__block">
                        <a href="#" className="posts__block__image">
                            <img src={article.src} alt={article.pid} />
                            <button
                                onClick={this.handlePopup.bind(this)}>sd</button>
                        </a>
                    </div>;
                })}
            </div>
        )
    }

Why is onClick={this.handlePopup.bind(this)} not working and how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2018-02-09
@cimonlebedev

Everything just turned out to be just need to set index as an additional argument

handlePopup=()=>{
        alert(123)
    };

    render(){
        return(
            <div className="posts">
                {this.props.articles.map((article, index)=>{
                    if(index !== 0){
                        return <div key={article.pid} className="posts__block">
                            <a href="#" className="posts__block__image" onClick={this.handlePopup.bind(this)}>
                                <img src={article.src} alt={article.pid} />
                                {index}
                            </a>
                        </div>;
                    }
                })}
            </div>
        )
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question