Question
Why don’t I need a ReactDOM.render() for each component?
Answer
As we will be dealing with multiple components in React, we will be coming across with the analogy that it’s structure is like a tree you have your main trunk which is also called the root component, that is the one that will have :
ReactDOM.render(<RootComponent/>, document.getElementById('root'));
there you can see
- we named our component
RootComponent
(but it is not a common practice, most likely the main component will have the nameapp
). - we are rendering it in the element with id of
root
, this is most likely a body tag or a div tag with id of root.
Once that is set, any other component will be related to that RootComponent
, so going back to the tree analogy, our trunk component will be render using ReactDOM, and so if it had three branches we would import the Branch
component in it and return them in the Trunk
's component’s render():
import React from 'react';
import ReactDOM from 'react-dom';
import Branch from '../Branch/Branch';
class Trunk extends React.Component {
render() {
return(
<div>
<Branch/>
<Branch/>
<Branch/>
</div>
)
}
}
ReactDOM.render(<Trunk/>, document.getElementById('root'));
There, Trunk will be rendered inside the element with id of root
and an instance of branch will be rendered inside of the div from Trunk, Now what if Branch had smaller branches? They can just be returned inside of Branch, let’s say each has three too:
import React from 'react';
import ReactDOM from 'react-dom';
import SmallerBranch from '../SmallerBranch/SmallerBranch';
class Branch extends React.Component {
render() {
return(
<div>
<SmallerBranch/>
<SmallerBranch/>
<SmallerBranch/>
</div>
)
}
}
export default Branch;
Now, the last part is important, because by using the keyword export we make the content of the file we just wrote into, available for import.
The same way with smaller branches having Leaf
component, and for each Leaf
component, they will all be only exported so they can be rendered in other components because they all are interconnected and so we only need one component to be rendered directly on an HTML element.