Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What classifies as a React functional component?

I am following a tutorial on Udemy where the instructor is trying to explain HOC.

To explain HOC, he created a function having a functional component (at least this is what he said). This is the code:

const withClass = (WrappedComponent, className) => {
     return (props) => (
         <div className={className}>
             <WrappedComponent {...props} />        
     </div>

   )
 }

The React documentation displays this example:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

And mentions:

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “functional” because they are literally JavaScript functions.

[Question]

In simpler words, is it safe to say that: Any function which takes props as an argument can be classified as a functional component? If not, can someone explain in a nutshell about functional components in React?


1 Answers

Any function which takes props as an argument can be classified as a functional component?

No, props is just the function argument, like all other normal function arguments. So if we define any function that accepts an argument it will not necessarily be a React functional component, like this is not a React component:

const Testing = props => {
   const a = 10;
   return a * props.a;
}

The important part is "If that component returns a React element", only then will it be a React functional component.

To make it more clear just define the below function in a separate file; it will not throw any error when you transpile:

const Test = props => props.key * 10;

But if you define this below component in a separate file without importing React, it will throw error, React is not defined, when you transpile:

const Test = props => <div>{props.key * 10}</div>;

Because JSX will get converted into React.createElement(....) and React will be required. The converted version of the above component will be:

var Test = function Test(props) {
  return React.createElement(
    "div",
    null,
    props.key * 10
  );
};

I will suggest, use Babel REPL and define both the functions and check the output.

like image 167
Mayank Shukla Avatar answered Aug 12 '26 12:08

Mayank Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!