@wordpress/element
Version:
Element React module for WordPress.
461 lines (247 loc) • 11.4 kB
Markdown
# Element
Element is a package that builds on top of [React](https://reactjs.org/) and provide a set of utilities to work with React components and React elements.
## Installation
Install the module
```bash
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`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/babel-preset-default#polyfill) in your code._
## Why React?
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](https://github.com/WordPress/gutenberg/tree/HEAD/packages/blocks/README.md), we observe the following technical requirements:
- An understanding of a block in terms of its underlying values (in the [random image example](https://github.com/WordPress/gutenberg/tree/HEAD/packages/blocks/README.md#example), a category)
- A means to describe the UI of a block given these values
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](https://reactjs.org/docs/components-and-props.html#functional-and-class-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.
## API
<!-- START TOKEN(Autogenerated API docs) -->
### Children
Object that provides utilities for dealing with React children.
### cloneElement
Creates a copy of an element with extended props.
_Parameters_
- _element_ `Element`: Element
- _props_ `?Object`: Props to apply to cloned element
_Returns_
- `Element`: Cloned element.
### Component
A base class to create WordPress Components (Refs, state and lifecycle hooks)
### concatChildren
Concatenate two or more React children objects.
_Parameters_
- _childrenArguments_ `...?Object`: Array of children arguments (array of arrays/strings/objects) to concatenate.
_Returns_
- `Array`: The concatenated value.
### createContext
Creates a context object containing two components: a provider and consumer.
_Parameters_
- _defaultValue_ `Object`: A default data stored in the context.
_Returns_
- `Object`: Context object.
### createElement
Returns a new element of given type. Type can be either a string tag name or another function which itself returns an element.
_Parameters_
- _type_ `?(string|Function)`: Tag name or element creator
- _props_ `Object`: Element properties, either attribute set to apply to DOM node or values to pass through to element creator
- _children_ `...Element`: Descendant elements
_Returns_
- `Element`: Element.
### createInterpolateElement
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 <span>string</span> with <a>a link</a> and a self-closing
<CustomComponentB/> tag"
You would have something like this as the conversionMap value:
```js
{
span: <span />,
a: <a href={ 'https://github.com' } />,
CustomComponentB: <CustomComponent />,
}
```
_Parameters_
- _interpolatedString_ `string`: The interpolation string to be parsed.
- _conversionMap_ `Record<string, Element>`: The map used to convert the string to a react element.
_Returns_
- `Element`: A wp element.
### createPortal
Creates a portal into which a component can be rendered.
_Related_
- <https://github.com/facebook/react/issues/10309#issuecomment-318433235>
_Parameters_
- _child_ `import('react').ReactElement`: Any renderable child, such as an element, string, or fragment.
- _container_ `HTMLElement`: DOM node into which element should be rendered.
### createRef
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.
### createRoot
Creates a new React root for the target DOM node.
_Related_
- <https://react.dev/reference/react-dom/client/createRoot>
_Changelog_
`6.2.0` Introduced in WordPress core.
### findDOMNode
Finds the dom node of a React component.
_Parameters_
- _component_ `import('react').ComponentType`: Component's instance.
### flushSync
Forces React to flush any updates inside the provided callback synchronously.
_Parameters_
- _callback_ `Function`: Callback to run synchronously.
### forwardRef
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_
- _forwarder_ `Function`: Function passed `props` and `ref`, expected to return an element.
_Returns_
- `Component`: Enhanced component.
### Fragment
A component which renders its children without any wrapping element.
### hydrate
> **Deprecated** since WordPress 6.2.0. Use `hydrateRoot` instead.
Hydrates a given element into the target DOM node.
_Related_
- <https://react.dev/reference/react-dom/hydrate>
### hydrateRoot
Creates a new React root for the target DOM node and hydrates it with a pre-generated markup.
_Related_
- <https://react.dev/reference/react-dom/client/hydrateRoot>
_Changelog_
`6.2.0` Introduced in WordPress core.
### isEmptyElement
Checks if the provided WP element is empty.
_Parameters_
- _element_ `*`: WP element to check.
_Returns_
- `boolean`: True when an element is considered empty.
### isValidElement
Checks if an object is a valid React Element.
_Parameters_
- _objectToCheck_ `Object`: The object to be checked.
_Returns_
- `boolean`: true if objectToTest is a valid React Element and false otherwise.
### lazy
_Related_
- <https://react.dev/reference/react/lazy>
### memo
_Related_
- <https://react.dev/reference/react/memo>
### Platform
Component used to detect the current Platform being used. Use Platform.OS === 'web' to detect if running on web environment.
This is the same concept as the React Native implementation.
_Related_
- <https://reactnative.dev/docs/platform-specific-code#platform-module> Here is an example of how to use the select method:
_Usage_
```js
import { Platform } from '@wordpress/element';
const placeholderLabel = Platform.select( {
native: __( 'Add media' ),
web: __(
'Drag images, upload new ones or select files from your library.'
),
} );
```
### PureComponent
_Related_
- <https://react.dev/reference/react/PureComponent>
### RawHTML
Component used to render unescaped HTML.
Note: The `renderElement` serializer will remove the `div` wrapper unless non-children props are present; typically when preparing a block for saving.
_Usage_
```jsx
import { RawHTML } from '@wordpress/element';
const Component = () => (
<RawHTML>
<h3>Hello world</h3>
</RawHTML>
);
// Edit: <div><h3>Hello world</h3></div>
// save: <h3>Hello world</h3>
```
_Parameters_
- _props_ `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.
### render
> **Deprecated** since WordPress 6.2.0. Use `createRoot` instead.
Renders a given element into the target DOM node.
_Related_
- <https://react.dev/reference/react-dom/render>
### renderToString
Serializes a React element to string.
_Parameters_
- _element_ `import('react').ReactNode`: Element to serialize.
- _context_ `[Object]`: Context object.
- _legacyContext_ `[Object]`: Legacy context object.
_Returns_
- `string`: Serialized element.
### startTransition
_Related_
- <https://react.dev/reference/react/startTransition>
### StrictMode
Component that activates additional checks and warnings for its descendants.
### Suspense
_Related_
- <https://react.dev/reference/react/Suspense>
### switchChildrenNodeName
Switches the nodeName of all the elements in the children object.
_Parameters_
- _children_ `?Object`: Children object.
- _nodeName_ `string`: Node name.
_Returns_
- `?Object`: The updated children object.
### unmountComponentAtNode
> **Deprecated** since WordPress 6.2.0. Use `root.unmount()` instead.
Removes any mounted element from the target DOM node.
_Related_
- <https://react.dev/reference/react-dom/unmountComponentAtNode>
### useCallback
_Related_
- <https://react.dev/reference/react/useCallback>
### useContext
_Related_
- <https://react.dev/reference/react/useContext>
### useDebugValue
_Related_
- <https://react.dev/reference/react/useDebugValue>
### useDeferredValue
_Related_
- <https://react.dev/reference/react/useDeferredValue>
### useEffect
_Related_
- <https://react.dev/reference/react/useEffect>
### useId
_Related_
- <https://react.dev/reference/react/useId>
### useImperativeHandle
_Related_
- <https://react.dev/reference/react/useImperativeHandle>
### useInsertionEffect
_Related_
- <https://react.dev/reference/react/useInsertionEffect>
### useLayoutEffect
_Related_
- <https://react.dev/reference/react/useLayoutEffect>
### useMemo
_Related_
- <https://react.dev/reference/react/useMemo>
### useReducer
_Related_
- <https://react.dev/reference/react/useReducer>
### useRef
_Related_
- <https://react.dev/reference/react/useRef>
### useState
_Related_
- <https://react.dev/reference/react/useState>
### useSyncExternalStore
_Related_
- <https://react.dev/reference/react/useSyncExternalStore>
### useTransition
_Related_
- <https://react.dev/reference/react/useTransition>
<!-- END TOKEN(Autogenerated API docs) -->
## Contributing to this package
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](https://www.npmjs.com/) and used by [WordPress](https://make.wordpress.org/core/) 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](https://github.com/WordPress/gutenberg/tree/HEAD/CONTRIBUTING.md).
<br /><br /><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>