React - Function Component

About

This page is about the writing of a component with the functional syntax

Example

In Jsx

  • A UD DOM component defining the Welcome tag
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
  • A React element using this DOM tag
const element = <Welcome name="Sarah Connor" />;
  • Rendering
ReactDOM.render(
  element,
  document.getElementById('root')
);
  • The standard mandatory “root” DOM node (placeholder for React DOM manipulation)
<div id="root"></div>
  • Output:

Syntax

A React component function is:

Native

In Native Javascript, with Create element

let Welcome = function(props){
  return React.createElement( 'h1', null. 'Hello, ', props.name )
};
let WelcomeFunctionComponent = React.createElement(Welcome, props);

Jsx

React - JSX

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

Management

Loop

See How to render a List of React Elements (Component, )?

Update

See:

Support

ReactCurrentDispatcher is null

If you get a problem where the ReactCurrentDispatcher is null followed by the rule of Hooks, There may be a possibility that you use a raw function and not a React component function.

To create a component from an exported function, use the React.createElement

Example: let's say:

  • that you have built a React Function Component as umd with the global name HelloWorld
  • if you want to render it as root

you would use this code.

// create the root
const root = ReactDOM.createRoot(document.getElementById('root'));
// Note the React.createElement
let HelloWorldComponent = React.createElement(HelloWorld, {});
// Render
root.render(HelloWorldComponent);
Task Runner