The component provides the solution for front-end complexity. It's just breaking the large pieces of complex UI parts into smaller pieces. So the component can be working independently and easily reusable.
The React component can write it in two ways, Class Component & Functional Components.
Before going to a detailed view about components, if you don’t have an idea about class. Please refer ES6 Class feature in our story and then continue.
A class component requires you to extend from React. Component. The render() method must define in your subclass if the parent is React. Component. Let’s see the simple example for a class.
When to use and why?
Class Components are Stateful components because they implement logic and state in it. React Lifecycle methods can be used inside class components. In our later stories, we will see the detailed view of React Lifecycle methods.
When to use and why?
Functional Components are Stateless components because they just accept the data and display it. Mainly it is used only for rendering UI. Lifecycle methods can not be used inside functional components.
Component using another Component Code Pen
Incase If you are going to use the component from other files or folder, then import the corresponding component to be here. eg) If there is a footer content which is available in /footer/Footer.js. Just import and use it.
import footer from ‘./footer/Footer.js’;
Class Component using another Code Pen
Understanding of props & default props Code Pen
props stand for properties and are being used for passing data from one component to another. Suppose if the props not passing the data from the parent component to the child, then the default props will provide the data. Let’s see this scenario with an example.
Will the <Employee /> return undefined or blank with No attributes?
Yes only if we are not set the default props. But in this code, we set default attribute values for “name” as ‘Morgan’ and “country” as “Ireland” in the Employee component. So the logical operator || used to set a fallback value, so whenever a prop is missing it displays the fallback value in place of the missing prop.
Looping an array in JSX Code Pen
In the last example, we manually called the employee component three times, suppose if the number of calls increased in such cases, use loop to avoid the component calls one by one.
Here we used the map method to return the values, why not used the forEach method? Code Pen
Let’s see the difference between forEach vs filter vs map vs reduce methods.
Hope it will give a basic view of Component & Props, Looping an array in JSX & Array iteration methods. Please write your questions for any doubts or corrections.
Let’s discuss the next feature of ReactJS in the next story.
Next topic: State in React