Search code examples
javascriptjqueryjsonreactjsweb-component

React - onClick for dynamically generated components


I'm writing a simple React app that queries an API, gets a JSON list of items, and creates individual buttons for each item. Upon completion of the API call, I change the state of the application to the JSON object, which causes the render() method to render a list of buttons.

axios.get('http://api_url')
.then(response => {
  this.setState({applicationJSON: response.data});
})
.catch(function (error) {
  console.log(error);
});

The problem is, I cannot attach an onClick to these buttons.

renderItems(text) {
return (
  <div>
    {
      text.map(function(name, index) {
        return <Button text={text[index].name} onClick={() => handleClick()} />
      })
    }
  </div>
);
}

Whenever I click one of these buttons, I get an error that handleClick() is not defined.

I know this is a problem with dynamically generated elements, as when I create a Button item in the constructor and bind the onClick to handleClick, handleClick() gets called.

What is the correct way to handle button clicks for dynamically generated components in React?


Solution

  • The reason it does not work is because when we use the function keyword (in the text.map), then this inside the function doesn't refer to the same this as the enclosing scope. You can either maintain a reference to the enclosing scope, e.g.

    renderItem(text) {
        const self = this;
            return (
                <div>
                    {text.map(function(name, index) {
                        return <Button text={text[index].name} onClick={self.handleClick} />
                    })}
                </div>
            );
        }
    

    Alternatively, you can make the whole thing a bit cleaner with some ES6 language features. Your mapping function can be simplified as well.

    class MyComponent extends React.Component {
        handleClick = (evt) => {
            // do something
        }
    
        renderItem = (text) => {
            return (
                <div>
                    {text.map(item => (
                        <Button text={item.name} onClick={this.handleClick} />
                    ))}
                </div>
            );
        }
    }
    

    This works because this inside lambda functions (the => functions) refers to the outer context of the function.