0

I'm having a bit of trouble understanding why classes in react function differently that plain js. Or am I missing something?

In the code I have, I understand that Header inherits the properties of 'props' so thanks to the constructor, I can use this.name inside the jsx. And als, in Header.proto resides the function doSomething. But when I call the function doSomething, the function can be called but doesn't have any access to 'this.name'. In plain js, it would have worked. so what's going on?

Why does binding / using an arrow function solve the problem?

Thanks in advance!

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export class Header extends Component {
    constructor(props) {
        super();
        this.name = props.name;
    }

    doSomething() {
        this.name = 5;

    }
    render() {

        return(
          <div>
        <button onClick={this.doSomething}></button>
          </div>
        );
    }

}
sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • 1
    [You have to bind the method to `this` in the constructor, or use an arrow function.](https://reactjs.org/docs/handling-events.html) – Tholle Aug 06 '18 at 19:51
  • "*Header inherits the properties of 'props' so thanks to the constructor*" - nope. The constructor initialises `Header` **instances**, and they don't **inherit** anything - they just get their own property. "*in Header.__proto__ resides the function doSomething*" - no, the `doSomething` method resides in `Header.prototype`, and is inherited by the instances – Bergi Aug 06 '18 at 19:51
  • "*when I call the function doSomething*" - you're not calling it. You are passing it around. And to get the button call the method on your particular `Header` instance, you need to bind it. – Bergi Aug 06 '18 at 19:54
  • Thanks for your answer Bergi, I still don't get it - what are those instances, what are their names? Unlike function constructor in js, it seems that Header gets the properties as if it was the instance itself? Why does binding solve the problem? – sir-haver Aug 06 '18 at 19:59
  • Hey I figured it out it just has to do with the button and executing the function on clicking the button, doesn't have anything to do with react – sir-haver Aug 06 '18 at 20:13

0 Answers0