Have you ever wondered how websites like Facebook and Instagram create fast and dynamic user interfaces? The answer lies in the power of React components. Components are the building blocks of user interfaces in React, allowing developers to create reusable pieces of code that can be used to build complex interfaces.
In this article, we'll explore the basics of components in React, how they work, and how to use them. Whether you're new to React or a seasoned developer, understanding components is essential to building fast and responsive user interfaces. So let's dive in and explore the exciting world of React components!
React is a popular open-source JavaScript library for building user interfaces on the web. It was developed by Facebook and is now maintained by Facebook and a community of developers.
React is known for its component-based architecture, which enables developers to create self-contained and reusable pieces of code called "components." These components can be used to build different parts of a web application and combined with other components to create more complex and dynamic user interfaces.
One of the critical features of React is its virtual DOM (Document Object Model), which allows it to update the UI efficiently. This results in faster rendering times and a smoother user experience.
React is highly customizable and can be used with other libraries and frameworks, making it a versatile development tool.
Also, check out our React Js Course and start your journey today to become part of vibrant community of developers.
Let us now learn what the components in React are.
Components in React
Remember the hustle of finishing the syllabus before an exam? What did we do then?
We divided our syllabus into different parts based on their weightage. In other words, we handled the dire situation by dividing our work.
Also, we take notes to use later on while studying, thereby providing reusability.
Now, instead of a syllabus, consider a user interface. What if we divided that into separate parts for easy handling and reusability?
Well, that's precisely what components in React are.
Apart from this, components in React are independent. To understand this, let us return to our grade 10 physics class.
Remember parallel and series circuits? If one of the components stopped working in a series circuit, the entire circuit would not work, while in parallel circuits, all the components are independent of each other.
Similarly, in components in React, if one of them has any errors, it is easier to find and fix without hampering the working of the rest of the components.
Thus, to formally define them,
Components in React are used to divide a user interface into independent components that can be handled easily and are reusable.
Sounds pretty useful, right? So, let's move further and learn about the types of components in React.
Functional components are simpler and more lightweight, while class-based components offer more features and flexibility. Functional components are typically used for simple UIs, while class-based components are better suited for complex and feature-rich UIs.
Functional components are easier to deal with, so the basics of components in React are shown with the help of functional components in the rest of the article.
Creating Components
What is the first thing we need to do when we're dealing with components?
That's right! We need to create a component.
While creating a component in React, the component's name should always start with an uppercase letter.
Given below is the syntax to create both functional and class components.
Creating Functional Components
Functional components are JavaScript functions that return a React element. Here's an example of a simple functional component.
function Animal( )
{
return <h2> Hello, I'm an animal! </h2>;
}
Here’s the complete code:
import React from 'react';
function Animal() {
return (
<h2> Hello, I'm an animal! </h2>
);
}
export function App() {
return (
<div>
<Animal />
</div>
);
}
export default App;
You could also define the Animal component as an arrow function expression:
To understand what "rendering" a component means in the easiest way possible, let us take the example of a simple function in any programming language.
Assume we write a sum function in Python that returns the sum of two numbers. To use that function, we call it as shown below:
def sum():
a,b = input("Enter two numbers ").split()
a = int(a)
b = int(b)
return a+b
#Calling the function
c = sum()
print(c)
Let’s try to understand components in React with respect to functions. Creating a function is analogous to creating a component, while calling a function is equivalent to rendering a component.
Now that we know what rendering a component is, let's see its syntax.
To learn more about rendering components in react, you can refer to this article.
Components with Props
Reading this heading, the first thing that comes to mind is, "What are props?"
"Props" is short for "properties." They are similar to function arguments for components. To understand this, let us consider our previous sum function example again.
def sum(a,b):
return a+b
a,b = input("Enter two numbers ").split()
a = int(a)
b = int(b)
c = sum(a,b)
print(c)
Here, the sum function has two arguments, a and b. Similarly, if we want to pass arguments to a component in React, we'll use props, as shown below:
Example
import React from 'react';
import ReactDOM from 'react-dom';
function Animal(props) {
return (
<h2> I am a/an {props.name}! </h2>
);
}
ReactDOM.render(<Animal name="Panda" />, document.getElementById('root'));
Output
Here, the name "Panda" is passed as an argument to the Animal component, thus giving the output "I am a/an Panda."
Components in Components
While solving complex programming problems, don't we make multiple functions and then call one inside another to reuse a portion of the code?
Of course, we do. After all, reusability is an important use of functions.
Similarly, we can call components inside another component. An example of that is given below.
Example
import React from 'react';
import ReactDOM from 'react-dom';
function Animal(props) {
return (
<h2> {props.name}! </h2>
);
}
function FavAnimal() {
return (
<>
<h1>What is your favorite animal?</h1>
<Animal name="Panda" />
</>
);
}
ReactDOM.render(<FavAnimal />, document.getElementById('root'));
Output
Components in Files
Do you remember what the main objective behind using components was?
You're right! We used it to divide the user interface.
For further division, we may want to divide the components according to their usage and save them in separate folders. But then, can we use the component in one folder and the code in another?
Of course, we can, and doing this is similar to importing a function from a library. We can import modules and files from other folders in our project using the import statement. When we want to import a module or file from another folder, we need to specify the path to that file relative to the current file.
Let's see the code for it to understand how it is done.
In the given code snippet, the Animal component is being imported from a file called Animal.jsx which is located in a folder that is in the same directory as the current file. The './' in the import statement specifies that the file is located in the current directory, and 'Animal.jsx' is the name of the file being imported.
Now that we've learned about components in React, let's address some of the frequently asked questions.
Components in React are used to divide a user interface into independent components that can be handled easily and are reusable.
Why are components used instead of the DOM approach?
Components are used for reusability and easy handling of applications.
What is the difference between functional and class components?
Functional components are defined using a function, while class components are defined using a class.
Can components be nested within other components?
Yes, components can be nested within other components to create complex UIs.
How can I reuse components in React?
Components can be reused in React by defining them once and then using them in multiple places within an application.
Conclusion
In this article, we learn about the basics of components in React. We discussed the different types of components, how to pass data using props, and much more.
Using components, developers can create fast and responsive UIs that are easy to maintain and extend. So, the next time you're building a web application, be sure to try React components!
To learn more about React, you can refer to these articles.