React: Pass State as Props to Child Components question about "this"

I passed the challenge, but I have one question:
why does this work:

class Navbar extends React.Component {

constructor(props) {

super(props);

}

render() {

return (

<div>

<h1>Hello, my name is: {this.props.name}</h1>

</div>

);

}

};

But not this:

class Navbar extends React.Component {

constructor(props) {

super(props);

}

render() {

return (

<div>

<h1>Hello, my name is: {props.name}</h1>

</div>

);

}

};

Why is the “this” necessary? The way I see it, both ways are passing props correctly.
Link to the challenge: https://learn.freecodecamp.org/front-end-libraries/react/pass-state-as-props-to-child-components/

1 Like

When you use props.name you’re trying to access key name in object props, which you didn’t declare before - it just does not exist.

When you use this.props.name you access this which is the component you are in (Navbar in this case). And the react component has props property by default, which collects provided data from parents.

Throw this and props to console in render:

render() {
    console.log(this)
    console.log(props)
    return (

And check your browser console - you will see the difference.

2 Likes

Your question does not regard React per se, but rather the idea of class in ES6. As you probably know, this in JS is the context of invocation. What would be the context of invocation in this case? A class is like a pattern/plan/recipe: it gives the guide for creating something, but it is not in itself that something that is created. A class is like the blueprint for a building, which is not a building in itself. And just like in this case, a blueprint is useful only as far as it leads us to building a building. So a class is useless without an instance of that class. Instances are created with the help of new, which triggers the constructor of the class. How do we know that this refers to these instances created through new. Let’s look at some code:

class First {
  constructor (name) {
    this.name = name;
  }
  
  getThis() {
    console.log(this);
  }
}

let one = new First('one');
one.getThis(); // First {name: "one"}
one.newProp = 'newOneProp';
one.getThis(); // First {name: "one", newProp: "newOneProp"}

So, it follows that by changing the instance called ‘one’ (by adding a prop called ‘newProp’) we changed the this the same way, which suggests that ‘one’ and this are the same in this case.

Now try to delete this from this.name in the ‘First’ class. For the first console.log you will get an empty object, because the property ‘name’ is no longer tied to the context of invocation, which is ‘one’.

1 Like

Thank you for the concise explanation. I was actually just right now reading an article about this: https://scotch.io/tutorials/better-javascript-with-es6-pt-ii-a-deep-dive-into-classes