1

Here is my code

import React,{ Component } from 'react';
import PTSearch from 'post-api-search';

export default class Navbar extends Component{
constructor(props) {
    super(props);

    this.state = {
        source: []
    };

    this.sourceSearch();
}

sourceSearch() {
    PTSearch({ 
        category: "",
        language: "en",
        country: ''
    }, "sources", (sources) => {
        this.setState({ 
            source: sources
        });
    });
}

loadSourceContent() {
    alert(1);
}

renderSource(data){
    return (
        <li title={data.description} onClick={this.loadSourceContent} key={data.name}>{data.name}</li>
    );
}

render(){
    return (
        <div>
            <button id="menu-toggle" className="menu-toggle"><span>Menu</span></button>
            <div id="theSidebar" className="sidebar">
                <button className="close-button fa fa-fw fa-close"></button>
                <div>
                    <img src="https://vignette.wikia.nocookie.net/clonewarsadventurescharacter/images/8/81/Superman-logo-transparent.png/revision/latest?cb=20131006162105" />
                </div>
                <ul className="source-list">
                    { this.state.source.slice(0, 10).map(this.renderSource) }
                </ul>
            </div>
        </div>
    );
};

}

I want to add an onclick event in each element of the li.But this code is not working for me. The issue is that when i click on <li> element it gives loadsourcecontent not defined error.

Thanks in advance and sorry about my English

  • Possible duplicate of [OnClick Event binding in React.js](https://stackoverflow.com/questions/27397266/onclick-event-binding-in-react-js) – Andreas Oct 07 '17 at 09:22

1 Answers1

0

You need to bind renderSource as the this context is not of the class.

constructor(props) {
    super(props);

    this.state = {
        source: []
    };
    this.renderSource = this.renderSource.bind(this);
    this.sourceSearch();
}

or use es6 arrow

Martin Dawson
  • 7,455
  • 6
  • 49
  • 92
  • @Sourav I'd split out this `renderSource` call to another class instead of putting it in a function on this class. E.G `{ this.state.source.slice(0, 10).map(data => ) }` as it's re-usable and clearer. – Martin Dawson Oct 07 '17 at 09:18