What makes component render to the screen?

Tell us what’s happening:
Hi,
Navbar component in this example renders to the screen, while MyApp does not. Codes are similar, apart from Navbar being a child of MyApp.
What makes Navbar render to the screen?

This question is to provide me with better understanding of how React works. Thanks for your time.

Your code so far


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

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36.

Challenge: Pass State as Props to Child Components

Link to the challenge:

What makes component render to the screen?

Unfortunately, at this stage the details are being hidden from you, but behind the scenes there is something like:

ReactDOM.render(<MyApp />, document.getElementById('root'));

where the first parameter is the root React component and the second parameter is where to render it - in this case it is looking in the HTML (also hidden from you at this point) for and element with the id of “root”.

Again, this is hidden from you at the moment, to make things smaller and easier to digest. You will learn it.

Navbar component in this example renders to the screen, while MyApp does not.

Why do you think MyApp doesn’t render. It does, it’s just that there is nothing there to see except for Navbar, it is just an invisible wrapper.

If you want to see it, you can change the _render_method in MyApp to:

render() {
  return (
    <div>
      <p>This is MyApp</p>
      <Navbar name= {this.state.name} />
    </div>
  );
}

Yes, React is confusing. It has a certain irreducible complexity and is very different that what came before. But once you get the hang of it, it is very powerful and has a certain logical elegance.

1 Like

Thank you very much Kevin. Yes, I find React more challenging than everything else I’ve learned so far. Unintentionally, I keep referring mentally to JavaScript and imagine bunch of objects being passed around or being drowned from. It gets confusing.
Now it is more clear. Thank you.