Welcome back, space traveler! As our journey surges forward, we are discovering more about the universe of React. Today, we will delve into React components, define Class and Functional components, learn why we use the latter, and create complex functional components with JSX. Let's go!
Class components, which were once vital in React, are a type of ES6 class. These components are robust, offering lifecycle methods, render methods, constructors, and the ability to handle state and props.
Below is an example of a simple Class Component:
Class components, however, faced limitations. Having to handle the this keyword complicated matters and resulted in more bugs. As JavaScript evolved, developers started preferring functional components due to their simplified syntax.
Functional components have been a part of React from the very beginning and are simply JavaScript functions. They accept props object as parameters and implement the render method to return React elements. These could be anything: a fragment of HTML, another functional component, or a class component.
But there's a crucial thing to remember. Every functional component must return only one parent element.
You might wonder, "What if I want to return multiple elements?" That's where wrapping elements come in handy. If your component needs to return multiple elements, they must all be wrapped in a parent element. This parent could be a div, a section, or any other HTML element.
Here's the example:
But what if you don't want an additional div in your HTML? This is where React Fragment comes into play! Fragments let you group a list of children without adding extra nodes to the DOM. Let's use React Fragment to refactor our Welcome component:
In this way, you can return multiple elements from a component. Functional components have shown their incredible power and versatility especially after the introduction of Hooks, as we will see going forward.
