score:2

Accepted answer

The solution was here:

class PickColor extends React.Component {
    getColorValue(event) {
        console.log(event.target.getAttribute("data-color"));
        this.props.color(event.target.getAttribute("data-color"));
    }
    render () {
        var colors = ['red', 'purple', 'yellow', 'green', 'blue'],
            colorsLink = [],
            that = this;

        colors.forEach(function(el){
            colorsLink.push(<li data-color={el} key={el} onClick={that.getColorValue.bind(that)} ref={el}>{el}</li>);
        });

        return (
            <ul>
                {colorsLink}
            </ul>
        );
    }
}

I had to bind "that" to the onClick inside the forEach loop

score:0

When you create a new function, like this:

function() {
    this.props.action(name);
});

This is bind to the new function context. Every function has a different this in javascript. You can solve this in a few ways:

Use arrow functions if you have them (they won't rebind this)

() => {
    this.props.action(name);
});

Rebind this with bind

function() {
    this.props.action(name);
}.bind(this));

Save this in a variable

var that = this;
function() {
    that.props.action(name);
});

Choose the first if you have a transpiler, like babel! Otherwise it's your call.

score:1

Issue is in this line:

onClick={that.getColorValue}

You forgot to bind the correct this (class context) with onClick event handler function because of that this.props is not accessible in getColorValue function.


Solutions:

Multiple Solutions are possible, use any one (all these changes are for PickColor component):

1- Inline binding of click handler:

onClick = { that.getColorValue.bind(this) }

2- Bind the method in the constructor:

constructor(props) {
    super(props);
    this.state = { };
    this.getColorValue = this.getColorValue.bind(this);
}

3- Using arrow function:

onClick = {e => that.getColorValue(e) }

4- Using class property syntax:

onclick = {this.getColorValue}

getColorValue = (e) => {
   console.log('e', this.props)
}

Related Query

More Query from same tag