H.Husain
H.Husain

Reputation: 473

TypeError: Cannot read property 'onSelect' of undefined

I have created a class component in react and need to pass props in render function while mapping, but I am getting the following error TypeError: Cannot read property 'onSelect' of undefined

Below is my component

class SelectLanguage extends Component {
    render() {
          let filterbrands = this.props.tvfilter.brand
          const filteredList = this.filterItems();

          if (filterbrands) {} else {}

          return (
              <div className="filter-options">
                  {filteredList &&
                      filteredList.map(item => (
                          <dl>
                              <dt className="mb-2">{item.title}</dt>
                              <input type="search" onChange={this.onSearchInputChange} className="search mb-2" placeholder="Search by Brand" />
                              {item.options.slice(0,this.state.itemsToShow).map(catname => (
                                  <dd
                                      key={catname.catgeory_name}
                                      className="mb-0"
                                  >
                                      <a href="#" onClick={props.onSelect.bind(null, item)}>{catname.catgeory_name}</a>
                                  </dd>
                              ))}
                          </dl>
                      ))}
                      <a className="btn btn-primary expandbutton" onClick={this.showMore}>{this.state.expanded ? (
                          <span>[ - less ]</span>
                          ) : (
                          <span>[ + more ]</span>
                          )
                      }</a>
              </div>
          );
      }
// PropTypes for SelectedLanguage
SelectLanguage.PropTypes = {
  selectedLanguage: PropTypes.string.isRequired,
  onSelect: PropTypes.func.isRequired
};
    }

The problem is in this anchor <a href="#" onClick={props.onSelect.bind(null, item)}>{catname.catgeory_name}</a>

Note: It works If I am using the function instead of class like this function SelectLanguage(props) {

Upvotes: 1

Views: 1513

Answers (3)

zdrsoft
zdrsoft

Reputation: 2587

Please, change this code:

<a href="#" onClick={props.onSelect.bind(null, item)}>{catname.catgeory_name}</a>

to

<a href="#" onClick={this.props.onSelect.bind(null, item)}>{catname.catgeory_name}</a>

Upvotes: 0

Najarana
Najarana

Reputation: 71

You are missing "this" before props.onSelect; you can define your props at the top of render for readability; eg const {onSelect } = this.props

Upvotes: 0

Youssef
Youssef

Reputation: 110

I believe you are missing "this" before setting your function as <a href="#" onClick={this.props.onSelect.bind(null, item)}>

Upvotes: 2

Related Questions