Michael Sheely
Michael Sheely

Reputation: 1031

React OnClick function won't bind and 'this' still shows undefined

I've built a React Component I have a list of buttons that will populate based upon an http call to get an arrary of customers, and it creates a button for each customer to retrieve details about that customer. Here is what I have so far:

export default class CustomerList extends React.Component {

  baseUrl = 'http://localhost/RevLocal.Operations.WebApi/api/';    

  getBillingAccounts = event =>  {
    event.preventDefault();
    alert('This is not working!');  
  }

  render() {
    var customers = [];
    if (this.props.customerList.map) {
        customers = this.props.customerList.map(function (c) {
            return <li className="list-group" key={c.id}>
                <button style={buttonStyle} className="btn btn-primary btn-block" onClick={this.getBillingAccounts}>
                    {c.id}-{c.companyName}
                </button>
            </li>
        });
    } else {
        customers = <li><h3>No customers found!</h3></li>
    }
    return (
        <ul style={{ list_style: 'none' }} className="list-group">
            {customers}
        </ul>
    );
  }
}

I've tried this several different way: I added a constructor and tried to bind the function, and I tried the inline bind as well, and none of it works. I'm hoping someone can look at this with a fresh pair of eyes and explain what's happening. Thanks in advance.

Upvotes: 0

Views: 52

Answers (1)

Ted
Ted

Reputation: 14927

I think it's a problem with the scope of this. Change this line:

this.props.customerList.map(function (c) {

to this:

this.props.customerList.map((c) => {

Upvotes: 3

Related Questions