Now that we know what a Virtual DOM is, we can proceed to learn about components.
A react application can be visualized like a tree. Each node in the tree is a component that renders some JSX. It is compulsory for components to return some JSX; it can’t return undefined.
Components help in making JSX code reusable and independent of where it is being rendered. In components, we use something known as props which means some data that has been passed from the parent to the child component. See the example below for a reference.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App(props) {
return <Welcome name="John Doe">;
}
Here if you see we are passing prop which is a name from the App to Welcome component. It’s always recommended to break down the code into smaller components to make them independent and reusable.
Consider the following code:
function MarvelHeros(){
return( <ul>
<li>Tony, stark</li> <li>Steve, Rogers</li> <li>Peter, Parker</li> <li>Bruce, Banner</li>
</ul>
}
This can be converted into smaller components and reused in this way:
function MarvelHeros(){
const herosList = [ "Tony, stark", "Steve, Rogers", "Peter, Parker", "Bruce, Banner"];
return (
<ul>
{herosList.map((hero)=><DisplayHero name={hero} />)}
</ul>
);
}
function DisplayHero({name}){
return <li> {name} </li>;
}
Components can be of 2 types: functional components and class-based components. You will learn the difference between these 2 in the upcoming lessons.