What are Components in React?
Components are the fundamental building blocks of React applications. They are independent, reusable pieces of code that work in isolation. The primary advantage of components is their ability to reduce redundancy and promote code reusability.
You can think of a component as a LEGO brick. When building a website, you combine many of these “bricks” to create the whole structure. This modular approach allows for flexible and efficient development of complex user interfaces.
React components come in two types: class components and functional components. While we won’t delve into the details here, it’s worth noting that class components have some drawbacks. They come with pre-loaded features that you might not need, which can make them more challenging to work with.
The React team now recommends building new applications using functional components and hooks. This approach is simpler and more flexible. For this reason, we’ll focus on functional components in this tutorial.
Creating a functional component in React
function Greet() {
return <h1>Hello World!</h1>;
}
//can also be written as:
const Greet = () => <h1>Hello World!</h1>
These are awfully familiar to Javascript Functions except they return a single HTML element.
The tags used are part of JSX which we will shortly discuss.
Nesting Components in React
React allows us to nest components within one another, enabling the creation of complex user interfaces. This approach not only helps eliminate redundant code but also promotes a modular structure. Components nested inside parent components are referred to as “child components.” By leveraging this hierarchical structure, developers can build more sophisticated and maintainable React applications.
let us take a look:
const Book = () => {
return (
<div>
<h1>Book name : Cracking The Coding Interview</h1>
<h2>Author : Gayle Laakmann McDowell</h2>
</div>
);
};
So here we have created a Book component. (Remember that React Components always start with uppercase letters) If we wanted to create more than one instance of this book component, we would nest these components.
const BookList = () => {
return (
<div>
<Book />
<Book />
</div>
);
};
const Book = () => {
return (
<div>
<h1>Book name : Cracking The Coding Interview</h1>
<h2>Author : Gayle Laakmann McDowell</h2>
</div>
);
};
In the code block above, we’ve created two components: Book and BookList. The Book component returns a div containing the book’s name and author, while BookList returns a div with two instances of the Book component.
This nesting technique allows us to easily create multiple instances of a component, enabling the construction of complex user interfaces with reusable, modular pieces.