Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

constTest = 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:

varTest = functionTest(props) {
  returnReact.createElement(
    "div",
    null,
    props.key * 10
  );
};

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

Solution 2:

When you create a function like this:

function MyComponent() {
  returnnull;
}

It is a normal JavaScript function, isn't it? But it can be turned into a React component. If you use react-preset that allows you to use JSX syntax you can turn this function into a component that renders null:

<Welcome />

will produce:

React.createElement(MyComponent, null);

So a functional component is a component that was created from a function not by extending the React base class (React.Component).

It's just two ways to define them. You can play around and see what's behind the scenes with the Babel online transpiler.

Solution 3:

Yes, a function, which takes props as an argument can be classified as a functional stateless react-component.

This function should return a valid component answer; e.g., React node, array, number, string or null.

Such a function has no state and you can't set up component lifecycle methods with it.

Your JSX code is transformed into a React.createElement function, that receives either a "native" component, e.g., div, span or function.

To clarify my answer I'll include the simplest React.createElement realisation (Dan Abramov posted this code on JS Bin some time ago):

// Necessary for JSX to workwindow.React = {
  createElement(type, props, ...children) {
    return {
      type,
      props: {
        ...props,
        children: children || props.children
      }
    }
  }
};

// What kind of node are we dealing with?functiongetNodeKind(node) {
  if (node === false || node == null) {
    // A hole: false, null, undefinedreturn'EMPTY';
  }
  if (typeof node === 'string' || typeof node === 'number') {
    // Text or number: 'Hello', 42return'TEXT';
  }
  if (Array.isArray(node)) {
    // An array of nodes!return'ARRAY';
  }
  if (typeof node.type === 'string') {
    // An element describing “host” (e.g. DOM) component: <div />return'HOST';
  }
  if (typeof node.type === 'function') {
    // An element describing “composite” (user-defined) component: <Foo />return'COMPOSITE';
  }
  thrownewError('Weird node: ' + node);
}

// To render a host element like <div />, we’ll generate// its tag markup and render children inside.// This is a simple implementation and doesn’t attempt to escape anything.functionrenderHostElementToString(el) {
  // Separate children from attributesconst { children, ...otherProps } = el.props;

  // Create an attribute string for markuplet attributes = Object.keys(el.props)
    .map(propName => propName + '=' + el.props[propName])
    .join(' ');
  
  // If attributes exist, prepend a space to separate from tagif (attributes) {
    attributes = ' ' + attributes;
  }
  
  // Create tag strings for markup// For host elements, type is the tag nameconst openingTag = '<' + el.type + attributes + '>';
  const closingTag ='</' + el.type + '>';
  
  return (
    openingTag +
    // Render children recursively!renderToString(children) +
    closingTag
  );
}

// To render a composite component like <Foo />,// we’ll call its type (`Foo`) with its props.// We will then recursively render it.functionrenderCompositeElementToString(el) {
  const renderedEl = el.type(el.props);
  returnrenderToString(renderedEl);
}

// Handle different types differently.functionrenderToString(node) {
  var kind = getNodeKind(node);
  switch (kind) {
    case'EMPTY':
      return'';
    case'TEXT':
      return node.toString();
    case'ARRAY':
      // Render each of themreturn node.map(renderToString).join('');
    case'HOST':
      // <div />returnrenderHostElementToString(node);
    case'COMPOSITE':
      // <Foo />returnrenderCompositeElementToString(node);
  }
}

// Let’s give it a try!functionBadge({ children }) {
  return (
    <div><hr />
      {children}
      <hr /></div>
  );
}

functionUserInfo({ name, location }) {
  return (
    <Badge>
      {name} lives in {location}.
    </Badge>
  );
}

functionApp() {
  return (
    <div><h1>
        Hello, React!
      </h1><UserInfoname="Dan"location="London"
      /></div>
  );
}

document.body.innerHTML = renderToString(<App />);

Solution 4:

A functional component in React:

  • Used for presenting static data
  • Can't handle fetching data
  • Easy to write

Example:

constHeader = () => {
  return<Text>Hello World!</Text>
}

Post a Comment for "What Classifies As A React Functional Component?"