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 , a , or any other HTML element.
