What is the difference between "this.state.name" and "this.props.name"?

Two questions about this challenge.
Q1: Why can’t we use "this.state.name’ instead of “this.props.name”?
Q2:Where does the output come from? Is it rendered by MyApp or Navbar as both of then have render part. Thanks!

  **Your code so far**

class MyApp extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    name: 'CamperBot'
  }
}
render() {
  return (
     <div>
       {/* Change code below this line */}
       <Navbar name = {this.state.name}/>
       {/* Change code above this line */}
     </div>
  );
}
};

class Navbar extends React.Component {
constructor(props) {
  super(props);
}
render() {
  return (
  <div>
    {/* Change code below this line */}
    <h1>Hello, my name is: {this.props.name}</h1>
    {/* Change code above this line */}
  </div>
  );
}
};

console.log(MyApp)
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Pass State as Props to Child Components

Link to the challenge:

State is the memory that is inside a component. Props are data that come from outside the component.

MyApp has internal state:

  this.state = {
    name: 'CamperBot'
  }

This is state inside the MyApp component - it is part of the “state” of the component. It did not come from outside the component, but was generated and is maintained within, and will persist between renders.

In the NavBar component, there is no state. There could be if someone wrote some, but right now, there is none. There is however props, data that is passed in from the outside, because the component was used like this:

<Navbar name = {this.state.name}/>

We are taking the data from this.state.name and passing it into Navbar as the props called “name”, so this.props.name. Don’t be fooled by them having the same name. If I had called the component as:

<Navbar nombre = {this.state.name}/>

Then inside Navbar, I would access it as this.props.nombre. The name is whatever name we give it.

1 Like

You made it clear to me, thanks!

I thought {this.state.name} is a value instead of props, but as you said, take it as a props, the logic is clear.