Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
@wordpress/element
Advanced tools
@wordpress/element is a package that provides utilities for working with React elements in the context of WordPress. It is essentially a thin abstraction layer over React, tailored to integrate seamlessly with the WordPress ecosystem.
Creating Elements
This feature allows you to create React elements using the `createElement` function, which is similar to React's `React.createElement`.
const { createElement } = require('@wordpress/element');
const element = createElement('div', { className: 'my-class' }, 'Hello World');
Component Class
You can define class components using the `Component` class provided by @wordpress/element, similar to React's `React.Component`.
const { Component } = require('@wordpress/element');
class MyComponent extends Component {
render() {
return createElement('div', null, 'Hello from MyComponent');
}
}
Hooks
The package supports React hooks like `useState`, allowing you to manage state in functional components.
const { useState } = require('@wordpress/element');
function MyFunctionalComponent() {
const [count, setCount] = useState(0);
return createElement('button', { onClick: () => setCount(count + 1) }, `Count: ${count}`);
}
React is a JavaScript library for building user interfaces. It is the core library that @wordpress/element is built upon. While @wordpress/element provides a WordPress-specific abstraction, React is more general-purpose and widely used across various web applications.
Preact is a fast 3kB alternative to React with the same modern API. It is designed to be a lightweight replacement for React, offering similar functionalities but with a smaller footprint. Unlike @wordpress/element, Preact is not tailored specifically for WordPress.
Inferno is an insanely fast, React-like library for building high-performance user interfaces on both the client and server. It aims to provide a similar API to React but with a focus on performance. Like Preact, it is not WordPress-specific.
Element is, quite simply, an abstraction layer atop React.
You may find yourself asking, "Why an abstraction layer?". For a few reasons:
createClass
, PropTypes
).On the wp.element
global object, you will find the following, ordered roughly by the likelihood you'll encounter it in your code:
Install the module
npm install @wordpress/element --save
This package assumes that your code will run in an ES2015+ environment. If you're using an environment that has limited or no support for such language features and APIs, you should include the polyfill shipped in @wordpress/babel-preset-default
in your code.
Let's render a customized greeting into an empty element.
Note: createRoot
was introduced with React 18, which is bundled with WordPress 6.2. Therefore it may be necessary to mount your component depending on which version of WordPress (and therefore React) you are currently using. This is possible by checking for an undefined import and falling back to the React 17 method of mounting an app using render
.
Assuming the following root element is present in the page:
<div id="greeting"></div>
We can mount our app:
import { createRoot, render, createElement } from '@wordpress/element';
function Greeting( props ) {
return createElement( 'span', null, 'Hello ' + props.toWhom + '!' );
}
const domElement = document.getElementById( 'greeting' );
const uiElement = createElement( Greeting, { toWhom: 'World' } );
if ( createRoot ) {
createRoot( domElement ).render( uiElement );
} else {
render( uiElement, domElement );
}
Refer to the official React Quick Start guide for a more thorough walkthrough, in most cases substituting React
and ReactDOM
with wp.element
in code examples.
At the risk of igniting debate surrounding any single "best" front-end framework, the choice to use any tool should be motivated specifically to serve the requirements of the system. In modeling the concept of a block, we observe the following technical requirements:
At its most basic, React provides a simple input / output mechanism. Given a set of inputs ("props"), a developer describes the output to be shown on the page. This is most elegantly observed in its function components. React serves the role of reconciling the desired output with the current state of the page.
The offerings of any framework necessarily become more complex as these requirements increase; many front-end frameworks prescribe ideas around page routing, retrieving and updating data, and managing layout. React is not immune to this, but the introduced complexity is rarely caused by React itself, but instead managing an arrangement of supporting tools. By moving these concerns out of sight to the internals of the system (WordPress core code), we can minimize the responsibilities of plugin authors to a small, clear set of touch points.
While not at all a requirement to use React, JSX is a recommended syntax extension to compose elements more expressively. Through a build process, JSX is converted back to the createElement
syntax you see earlier in this document.
If you've configured Babel for your project, you can opt in to JSX syntax by specifying the pragma
option of the transform-react-jsx
plugin in your .babelrc
configuration.
{
"plugins": [
[
"transform-react-jsx",
{
"pragma": "createElement"
}
]
]
}
This assumes that you will import the createElement
function in any file where you use JSX. Alternatively, consider using the @wordpress/babel-plugin-import-jsx-pragma
Babel plugin to automate the import of this function.
Object that provides utilities for dealing with React children.
Creates a copy of an element with extended props.
Parameters
WPElement
: Element?Object
: Props to apply to cloned elementReturns
WPElement
: Cloned element.A base class to create WordPress Components (Refs, state and lifecycle hooks)
Concatenate two or more React children objects.
Parameters
...?Object
: Array of children arguments (array of arrays/strings/objects) to concatenate.Returns
Array
: The concatenated value.Creates a context object containing two components: a provider and consumer.
Parameters
Object
: A default data stored in the context.Returns
Object
: Context object.Returns a new element of given type. Type can be either a string tag name or another function which itself returns an element.
Parameters
?(string|Function)
: Tag name or element creatorObject
: Element properties, either attribute set to apply to DOM node or values to pass through to element creator...WPElement
: Descendant elementsReturns
WPElement
: Element.This function creates an interpolated element from a passed in string with specific tags matching how the string should be converted to an element via the conversion map value.
Usage
For example, for the given string:
"This is a string with a link and a self-closing tag"
You would have something like this as the conversionMap value:
{
span: <span />,
a: <a href={ 'https://github.com' } />,
CustomComponentB: <CustomComponent />,
}
Parameters
string
: The interpolation string to be parsed.Record<string, WPElement>
: The map used to convert the string to a react element.Returns
WPElement
: A wp element.Creates a portal into which a component can be rendered.
Related
Parameters
import('./react').WPElement
: Any renderable child, such as an element, string, or fragment.HTMLElement
: DOM node into which element should be rendered.Returns an object tracking a reference to a rendered element via its current
property as either a DOMElement or Element, dependent upon the type of element rendered with the ref attribute.
Returns
Object
: Ref object.Creates a new React root for the target DOM node.
Related
Changelog
6.2.0
Introduced in WordPress core.
Finds the dom node of a React component.
Parameters
import('./react').WPComponent
: Component's instance.Forces React to flush any updates inside the provided callback synchronously.
Parameters
Function
: Callback to run synchronously.Component enhancer used to enable passing a ref to its wrapped component. Pass a function argument which receives props
and ref
as its arguments, returning an element using the forwarded ref. The return value is a new component which forwards its ref.
Parameters
Function
: Function passed props
and ref
, expected to return an element.Returns
WPComponent
: Enhanced component.A component which renders its children without any wrapping element.
Deprecated since WordPress 6.2.0. Use
hydrateRoot
instead.
Hydrates a given element into the target DOM node.
Related
Creates a new React root for the target DOM node and hydrates it with a pre-generated markup.
Related
Changelog
6.2.0
Introduced in WordPress core.
Checks if the provided WP element is empty.
Parameters
*
: WP element to check.Returns
boolean
: True when an element is considered empty.Checks if an object is a valid WPElement.
Parameters
Object
: The object to be checked.Returns
boolean
: true if objectToTest is a valid WPElement and false otherwise.Related
Related
Component used to detect the current Platform being used. Use Platform.OS === 'web' to detect if running on web enviroment.
This is the same concept as the React Native implementation.
Related
Usage
import { Platform } from '@wordpress/element';
const placeholderLabel = Platform.select( {
native: __( 'Add media' ),
web: __(
'Drag images, upload new ones or select files from your library.'
),
} );
Component used as equivalent of Fragment with unescaped HTML, in cases where it is desirable to render dangerous HTML without needing a wrapper element. To preserve additional props, a div
wrapper will be created if any props aside from children
are passed.
Parameters
RawHTMLProps
: Children should be a string of HTML or an array of strings. Other props will be passed through to the div wrapper.Returns
JSX.Element
: Dangerously-rendering component.Deprecated since WordPress 6.2.0. Use
createRoot
instead.
Renders a given element into the target DOM node.
Related
Serializes a React element to string.
Parameters
import('react').ReactNode
: Element to serialize.[Object]
: Context object.[Object]
: Legacy context object.Returns
string
: Serialized element.Related
Component that activates additional checks and warnings for its descendants.
Related
Switches the nodeName of all the elements in the children object.
Parameters
?Object
: Children object.string
: Node name.Returns
?Object
: The updated children object.Deprecated since WordPress 6.2.0. Use
root.unmount()
instead.
Removes any mounted element from the target DOM node.
Related
Related
Related
Related
Related
Related
Related
Related
Related
Related
Related
Related
Related
Related
Related
Related
This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main contributor guide.
FAQs
Element React module for WordPress.
We found that @wordpress/element demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 23 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.