React

Hi there. I didnt understand this question : quiz

“What will this equal in updateFunction when a user clicks on the ChildExample rendered below?”

import React from ‘react’;
import ReactDOM from ‘react-dom’;

class ParentExample extends React.Component {
constructor(props) {
super(props);

this.updateFunction = this.updateFunction.bind(this);

}

updateFunction(updatedValue) {
this.setState({value: updatedValue});
},

render() {
return <ChildExample onClick={this.updateFunction} />;
}
});

ReactDOM.render(, document.getElementById(‘app’));

Hi there!

The ParentExample component renders another component called ChildExample, while passing its updateFunction method to ChildExample as a prop called onClick. So when the user clicks on the ChildExample component, that updateFunction method will be called. However notice that in the updateFunction method definition there’s a call to this.setState({value: updatedValue}). How could we tell if the this keyword is referring to the ChildExample instance or the ParentExample that rendered ChildExample?

In the ParentExample constructor, the following line of code binds the updateFunction method’s this reference to ParentExample:

this.updateFunction = this.updateFunction.bind(this);

It means that any this keyword used in the method will reference the ParentExample component. So the correct answer to the question “What will this equal in updateFunction when a user clicks on the ChildExample rendered below?” is:

“The ParentExample that rendered the clicked ChildExample.”

2 Likes