### Start Local WordPress Environment
Source: https://github.com/10up/block-components/blob/develop/CONTRIBUTING.md
Starts the local WordPress environment and imports test media. The environment will be available at http://localhost:8888. Run this from the repository root.
```bash
npm run start-test-env
```
--------------------------------
### Install Dependencies with npm CI
Source: https://github.com/10up/block-components/blob/develop/CONTRIBUTING.md
Installs all project dependencies for both the root package and the example workspace. Run this from the repository root.
```bash
npm ci
```
--------------------------------
### Watch for Changes with npm Run Start
Source: https://github.com/10up/block-components/blob/develop/CONTRIBUTING.md
Builds assets and watches for changes during development. Run this from the repository root.
```bash
npm run start
```
--------------------------------
### API Fetch Example for Content Picker
Source: https://github.com/10up/block-components/blob/develop/components/content-picker/readme.md
This example demonstrates how the `contentTypes` prop is used to construct a REST API request for searching content. It shows the parameters passed to `apiFetch` for filtering by keyword, subtype, and type.
```javascript
apiFetch( {
path: `wp/v2/search/?search="${keyword}"&subtype="${contentTypes.join(',')}"&type=${mode}`
} )...
```
--------------------------------
### Build Assets with npm Run Build
Source: https://github.com/10up/block-components/blob/develop/CONTRIBUTING.md
Builds the assets for both the main package and the example workspace. Run this from the repository root.
```bash
npm run build
```
--------------------------------
### PostTermList Usage Example
Source: https://github.com/10up/block-components/blob/develop/components/post-term-list/readme.md
Demonstrates how to import and use the PostTermList component with custom styling and nested sub-components for displaying terms.
```javascript
import { PostTermList } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### Get all available Icon Sets
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Retrieves a list of all available icon sets, each with its name and label.
```APIDOC
## Get all available Icon Sets
### Description
Retrieves a list of all available icon sets, each with its name and label.
### Method
JavaScript
### Endpoint
`select('tenup/icons').getIconSets()`
### Response
#### Success Response (200)
- **Array** - A list of icon set objects, each containing `name` and `label` properties.
### Response Example
```json
[
{ "name": "example/theme", "label": "Example" icons: [] },
{ "name": "core/dashicons", "label": "Dashicons" icons: [] },
]
```
```
--------------------------------
### Import and Use PostDate Component
Source: https://github.com/10up/block-components/blob/develop/components/post-date/readme.md
Demonstrates how to import and use the PostDate component within a React component. Ensure '@10up/block-components' is installed.
```javascript
import { PostDate } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### Get all icons from an Icon Set
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Retrieves all icons belonging to a specified icon set.
```APIDOC
## Get all icons from an Icon Set
### Description
Retrieves all icons belonging to a specified icon set.
### Method
JavaScript
### Endpoint
`select('tenup/icons').getIcons( 'core/dashicons' );`
### Parameters
#### Path Parameters
- **name** (string) - Required - The name of the icon set from which to retrieve icons.
### Response
#### Success Response (200)
- **Array** - A list of icon objects, each containing `source`, `name`, and `label` properties.
### Response Example
```json
[
{
"source": "...",
"name": "...",
"label": "..."
},
{
"source": "...",
"name": "...",
"label": "..."
}
]
```
```
--------------------------------
### Get a Singular Icon from an Icon Set
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Fetch a specific icon by its name from a given icon set. This selector is used to get the details of a single icon.
```js
select('tenup/icons').getIcon( 'core/dashicons', 'smiley' );
```
```json
{
source: "...",
name: "...",
label: "..."
}
```
--------------------------------
### ClipboardButton Usage Example
Source: https://github.com/10up/block-components/blob/develop/components/clipboard-button/readme.md
Demonstrates how to import and use the ClipboardButton component in a React application. Configure the text to copy, a success callback, custom labels for the button states, and the disabled attribute.
```javascript
import { ClipboardButton } from '@10up/block-components';
const MyComponent = () => {
return (
);
};
```
--------------------------------
### Get All Icons from an Icon Set
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Retrieve all icons belonging to a specified icon set. This returns an array of icon objects.
```js
select('tenup/icons').getIcons( 'core/dashicons' );
```
```json
[
{
source: "...",
name: "...",
label: "..."
},
{
source: "...",
name: "...",
label: "..."
}
]
```
--------------------------------
### Usage Example
Source: https://github.com/10up/block-components/blob/develop/components/rich-text-field/readme.md
Demonstrates how to use the RichTextField component within a WordPress block's edit function, specifically within `InspectorControls` and a `Modal`.
```APIDOC
## Usage
```jsx
import { InspectorControls } from '@wordpress/block-editor';
import { Modal, PanelBody, Button } from '@wordpress/components';
import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { RichTextField } from '@10up/block-components';
function BlockEdit(props) {
const { attributes, setAttributes } = props;
const { sidebarNote, modalNote } = attributes;
const [isOpen, setIsOpen] = useState(false);
return (
<>
setAttributes({ sidebarNote: value })}
placeholder={__('Type and select to see the toolbar…', 'your-textdomain')}
/>
{isOpen && (
setIsOpen(false)}
>
setAttributes({ modalNote: value })}
allowedFormats={['core/bold', 'core/italic', 'core/link']}
/>
)}
>
);
}
```
```
--------------------------------
### Get an Icon Set by name
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Retrieves a specific icon set by its unique name.
```APIDOC
## Get an Icon Set by name
### Description
Retrieves a specific icon set by its unique name.
### Method
JavaScript
### Endpoint
`select('tenup/icons').getIconSet( 'core/dashicons' );`
### Parameters
#### Path Parameters
- **name** (string) - Required - The name of the icon set to retrieve.
### Response
#### Success Response (200)
- **Object** - The icon set object, containing `name`, `label`, and `icons` properties.
### Response Example
```json
{
"name": "core/dashicons",
"label": "Dashicons"
"icons": []
}
```
```
--------------------------------
### Get Taxonomy Data with useTaxonomy
Source: https://github.com/10up/block-components/blob/develop/hooks/use-taxonomy/readme.md
Import and use the `useTaxonomy` hook to fetch taxonomy data, such as post tags. Ensure you handle the loading state using the resolved flag before rendering component content.
```javascript
import { useTaxonomy } from '@10up/block-components';
function BlockEdit(props) {
const [postTag, hasResolvedPostTag] = useTaxonomy('post_tag');
if ( ! hasResolvedPostTag ) {
return
}
return (
...
);
}
```
--------------------------------
### Image Component Usage
Source: https://github.com/10up/block-components/blob/develop/components/image/readme.md
Example of how to use the Image component within a React block, including handling image selection and focal point changes.
```APIDOC
## Image Component
### Description
The Image component allows you to easily add images to your custom blocks without needing to manually worry about loading states etc. It renders a `` component in place of the image if the id is not set and shows a spinner when the image is still loading.
### Props
| Name | Type | Default | Description |
|---|---|---|---|
| `id` | `number` | `null` | Image ID |
| `onSelect` | `Function` | `null` | Callback that gets called with the new image when one is selected |
| `size` | `string` | `large` | Name of the image size to be displayed |
| `focalPoint` | `object` | `{x:0.5,y:0.5}` | Optional focal point object. |
| `onChangeFocalPoint` | `function` | `undefined` | Callback that gets called with the new focal point when it changes. (Is required for the FocalPointPicker to appear) |
| `labels` | `object` | `{}` | Pass in an object of labels to be used by the `MediaPlaceholder` component under the hook. Allows the sub properties `title` and `instructions` |
| `canEditImage` | `boolean` | `true` | whether or not the image can be edited by in the context its getting viewed. Controls whether a placeholder or upload controls should be shown when no image is present |
| `allowedTypes` | `array` | `['image']` | Array of [unique file type specifiers](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers): file extensions, [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types), `image` |
| `...rest` | `*` | `null` | any additional attributes you want to pass to the underlying `img` tag |
```
--------------------------------
### Get Singular Icon from an Icon Set
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Retrieves a single icon by its name from a specified icon set.
```APIDOC
## Get Singular Icon from an Icon Set
### Description
Retrieves a single icon by its name from a specified icon set.
### Method
JavaScript
### Endpoint
`select('tenup/icons').getIcon( 'core/dashicons', 'smiley' );`
### Parameters
#### Path Parameters
- **setName** (string) - Required - The name of the icon set.
- **iconName** (string) - Required - The name of the icon to retrieve.
### Response
#### Success Response (200)
- **Object** - The icon object, containing `source`, `name`, and `label` properties.
### Response Example
```json
{
"source": "...",
"name": "...",
"label": "..."
}
```
```
--------------------------------
### Unregister Extension from Multiple Blocks
Source: https://github.com/10up/block-components/blob/develop/api/register-block-extension/readme.md
This example shows how to unregister an extension from multiple blocks simultaneously by providing an array of block names. This mirrors the behavior of registerBlockExtension for multiple blocks.
```javascript
// Works with multiple blocks too (same as registerBlockExtension)
unregisterBlockExtension(['core/group', 'core/columns'], 'background-patterns');
```
--------------------------------
### Get All Available Icon Sets
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Retrieve all defined icon sets from the data store. This selector returns an array of objects, each representing an icon set with its name and label.
```js
select('tenup/icons').getIconSets();
```
```json
[
{ name: 'example/theme', label: 'Example' icons: [] },
{ name: 'core/dashicons', label: 'Dashicons' icons: [] },
]
```
--------------------------------
### Get All Terms from Taxonomy with useAllTerms
Source: https://github.com/10up/block-components/blob/develop/hooks/use-all-terms/readme.md
Import and use the `useAllTerms` hook in your block's edit component to fetch terms. Pass the taxonomy slug (e.g., 'category') as an argument. The hook returns an array of terms and a boolean flag indicating resolution status, which should be checked before rendering term-dependent UI.
```javascript
import { useAllTerms } from '@10up/block-components';
function BlockEdit(props) {
const [categories, hasResolvedCategories] = useAllTerms('category');
if ( ! hasResolvedCategories ) {
return
}
return (
...
);
}
```
--------------------------------
### Get an Icon Set by Name
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Fetch a specific icon set by its unique name. This is useful for accessing the icons within a particular set.
```js
select('tenup/icons').getIconSet( 'core/dashicons' );
```
```json
{
name: 'core/dashicons',
label: 'Dashicons'
icons: []
}
```
--------------------------------
### Importing from Base Entry Point
Source: https://github.com/10up/block-components/blob/develop/README.md
Use this method to import components from the main library entry point. Ensure your project supports the required import syntax.
```jsx
import { ContentPicker } from '@10up/block-components';
import { useAllTerms } from '@10up/block-components';
import { registerBlockExtension } from '@10up/block-components';
import { iconStore } from '@10up/block-components';
```
--------------------------------
### Creating a Sticky Notice with Link using useMaxInnerBlocks
Source: https://github.com/10up/block-components/blob/develop/hooks/use-max-inner-blocks/readme.md
Configure a sticky, in-canvas notice with an explicit dismiss button and an "Learn more" link by setting `noticeOptions.type` to 'default' and providing `explicitDismiss` and `actions`.
```javascript
import { useMaxInnerBlocks } from '@10up/block-components';
import { __ } from '@wordpress/i18n';
function BlockEdit({ clientId }) {
useMaxInnerBlocks({
clientId,
max: 3,
message: __('You can only add up to 3 cards.', 'your-textdomain'),
noticeOptions: {
type: 'default',
explicitDismiss: true,
actions: [
{
label: __('Learn more', 'your-textdomain'),
url: 'https://example.com/docs/cards-block',
},
],
},
});
return (
// ...
);
}
```
--------------------------------
### Using ColorSetting Component
Source: https://github.com/10up/block-components/blob/develop/components/color-settings/readme.md
Demonstrates how to import and use the ColorSetting component within a React component. It shows how to pass props like label, help, colors, value, and the onChange handler.
```javascript
import { ColorSetting } from '@10up/block-components';
function MyComponent( props ) {
return (
setColor( color ) }
/>
)
}
```
--------------------------------
### Using Counter and CircularProgressBar
Source: https://github.com/10up/block-components/blob/develop/components/counter/readme.md
Demonstrates how to import and use both the Counter and CircularProgressBar components. Ensure you have imported them from '@10up/block-components'.
```js
import { Counter, CircularProgressBar } from '@10up/block-components';
function MyComponent( props ) {
return (
<>
>
);
}
```
--------------------------------
### Import and Use Icon Store Selector
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
Import the iconStore and use the select function to access the icons data store.
```js
import { iconStore } from '@10up/block-components';
select(iconStore).getIconSets();
```
--------------------------------
### Basic ContentPicker Usage
Source: https://github.com/10up/block-components/blob/develop/components/content-picker/readme.md
Demonstrates how to use the ContentPicker component for basic post or page selection. Configure the mode, label, and allowed content types.
```javascript
import { ContentPicker } from '@10up/block-components';
function MyComponent( props ) {
return (
{ console.log(pickedContent) } }
mode="post"
label={ "Please select a Post or Page:" }
contentTypes={ [ 'post', 'page' ] }
/>
)
}
```
--------------------------------
### Basic PostAuthor Usage
Source: https://github.com/10up/block-components/blob/develop/components/post-author/readme.md
Demonstrates how to import and use the PostAuthor component with its sub-components to display author information within a block editor context. Ensure PostContext is available for data handling.
```javascript
import { PostAuthor } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### Import and Use useSelectedTermIds Hook
Source: https://github.com/10up/block-components/blob/develop/hooks/use-selected-term-ids/readme.md
Demonstrates how to import and utilize the useSelectedTermIds hook within a React component to get selected category IDs.
```javascript
import { useSelectedTermIds } from '@10up/block-components';
function BlockEdit(props) {
const [selectedCategoryIds, hasResolvedSelectedCategoryIds] = useSelectedTermIds('category');
return (
...
);
}
```
--------------------------------
### Basic PostCategoryList Usage
Source: https://github.com/10up/block-components/blob/develop/components/post-category-list/readme.md
Demonstrates how to import and use the PostCategoryList component with its sub-components to render category links. This is useful for displaying category information within a WordPress block context.
```javascript
import { PostCategoryList } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### Display Post Excerpt
Source: https://github.com/10up/block-components/blob/develop/components/post-excerpt/readme.md
Import and use the PostExcerpt component to display the current post's excerpt. It accepts a className prop for styling.
```javascript
import { PostExcerpt } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### Basic usePopover Hook Usage
Source: https://github.com/10up/block-components/blob/develop/hooks/use-popover/readme.md
Demonstrates how to import and use the usePopover hook to toggle a Popover component. Requires importing usePopover from '@10up/block-components'.
```javascript
import { usePopover } from '@10up/block-components';
function BlockEdit(props) {
const { toggleProps, Popover } = usePopover();
return (
<>
I'm rendered inside a Popover
>
);
}
```
--------------------------------
### Basic PostContext Usage
Source: https://github.com/10up/block-components/blob/develop/components/post-context/readme.md
Demonstrates how to wrap child components with PostContext to provide a specific post ID and type. This is useful for setting a default post or for testing.
```javascript
import { PostContext, PostTitle } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### Retrieve Primary Term using usePrimaryTerm
Source: https://github.com/10up/block-components/blob/develop/hooks/use-primary-term/readme.md
Import and use the usePrimaryTerm hook to get the primary term for a 'category' taxonomy. This hook requires Yoast SEO to be active.
```javascript
import { usePrimaryTerm } from '@10up/block-components';
function BlockEdit(props) {
const [primaryCategory, isSupportingCategory] = usePrimaryTerm('category');
return (
...
);
}
```
--------------------------------
### Integrate MediaToolbar in BlockControls
Source: https://github.com/10up/block-components/blob/develop/components/media-toolbar/readme.md
Demonstrates how to import and use the MediaToolbar component within the BlockControls of a WordPress block. It shows how to manage image selection and removal by updating block attributes.
```javascript
import { __ } from '@wordpress/i18n';
import { BlockControls } from '@wordpress/block-editor';
import { MediaToolbar } from '@10up/block-components';
function BlockEdit(props) {
const { attributes, setAttributes } = props;
const { imageId } = attributes;
function handleImageSelect( image ) {
setAttributes({imageId: image.id});
}
function handleImageRemove() {
setAttributes({imageId: null})
}
return (
<>
...
>
)
}
```
--------------------------------
### Importing Individual Modules
Source: https://github.com/10up/block-components/blob/develop/README.md
Import individual modules directly from their specific paths to improve tree-shaking and reduce bundle size. This is recommended when using only a subset of the library.
```jsx
import { ContentPicker } from '@10up/block-components/components/content-picker';
import { useAllTerms } from '@10up/block-components/hooks/use-all-terms';
import { registerBlockExtension } from '@10up/block-components/api/register-block-extension';
import { iconStore } from '@10up/block-components/stores/icons';
```
--------------------------------
### Access and Modify Parent Block Attributes
Source: https://github.com/10up/block-components/blob/develop/hooks/use-block-parent-attributes/readme.md
Use this hook within a block's edit component to get the parent block's attributes and update them. Ensure the hook is imported from '@10up/block-components'.
```js
import { useBlockParentAttributes } from '@10up/block-components';
function BlockEdit(props) {
const [parentAttributes, setParentAttributes] = useBlockParentAttributes();
return (
setParentAttributes({ title: value }) }
/>
);
}
```
--------------------------------
### Get Current Post Data with `usePost`
Source: https://github.com/10up/block-components/blob/develop/hooks/use-post/readme.md
Import and use the `usePost` hook within a React component to access post details like ID, type, and editability. This hook automatically references the correct post based on its context.
```javascript
import { usePost } from '@10up/block-components';
function BlockEdit(props) {
const {
postId,
postType,
isEditable
} = usePost();
return (
...
);
}
```
--------------------------------
### registerBlockExtension Usage
Source: https://github.com/10up/block-components/blob/develop/api/register-block-extension/readme.md
Demonstrates how to use the registerBlockExtension API to add custom settings to a block. This includes defining additional attributes, a component for the editor interface, and functions for generating class names and inline styles.
```APIDOC
## registerBlockExtension
### Description
This function is a wrapper to make it easier to add custom settings which produce classnames or inline styles to any blocks. It simplifies the process of registering custom attributes, modifying the block's edit function, and adding new classnames/inline styles to both the editor and the frontend.
### Method
`registerBlockExtension(blockName, options)`
### Parameters
#### Path Parameters
- **blockName** (string|string[]) - Required - Name of the block or array with multiple block names the options should get added to.
#### Query Parameters
- **options** (object) - Required - Configuration object for the block extension.
- **extensionName** (string) - Required - Unique Identifier of the option added.
- **attributes** (object) - Optional - Block Attributes that should get added to the block.
- **classNameGenerator** (function) - Optional - Function that gets passed the attributes of the block to generate a class name string.
- **inlineStyleGenerator** (function) - Optional - Function that gets passed the attributes of the block to generate an inline style object.
- **Edit** (function) - Optional - BlockEdit component like in `registerBlockType` only without the actual block. So only using slots like the `InspectorControls` is advised.
- **order** (string) - Optional - The order in which the extension should be called in relation to the original BlockEdit component. Can be `before` or `after`. Defaults to `after`.
### Request Example
```javascript
import { registerBlockExtension } from '@10up/block-components';
const additionalAttributes = {
hasBackgroundPattern: {
type: 'boolean',
default: false,
},
backgroundPatternShape: {
type: 'string',
default: 'dots',
},
backgroundPatternColor: {
type: 'string',
default: 'green'
}
};
function BlockEdit(props) { ... }
function generateClassNames(attributes) { ... }
function generateInlineStyles(attributes) { ... }
registerBlockExtension(
'core/group',
{
extensionName: 'background-patterns',
attributes: additionalAttributes,
classNameGenerator: generateClassNames,
inlineStyleGenerator: generateInlineStyles,
Edit: BlockEdit,
order: 'before',
}
);
```
### Response
This function does not return a value. It registers the block extension with the WordPress editor.
```
--------------------------------
### Customizing Notice Icon with useMaxInnerBlocks
Source: https://github.com/10up/block-components/blob/develop/hooks/use-max-inner-blocks/readme.md
Override the default notice icon by passing a React element to the `noticeOptions.icon` prop. This example uses a lock icon from @wordpress/icons and sets `fill="currentColor"` to ensure it inherits the notice color.
```javascript
import { useMaxInnerBlocks } from '@10up/block-components';
import { Icon, lock } from '@wordpress/icons';
import { __ } from '@wordpress/i18n';
function BlockEdit({ clientId }) {
useMaxInnerBlocks({
clientId,
max: 3,
message: __('You can only add up to 3 cards.', 'your-textdomain'),
noticeOptions: {
icon: ,
},
});
return (
// ...
);
}
```
--------------------------------
### Basic ContentSearch Usage
Source: https://github.com/10up/block-components/blob/develop/components/content-search/readme.md
Demonstrates the basic implementation of the ContentSearch component. Use this for a standard search interface for posts or pages.
```javascript
import { ContentSearch } from '@10up/block-components';
function MyComponent( props ) {
return (
{ console.log(item) } }
mode="post"
label={ "Please select a Post or Page:" }
contentTypes={ [ 'post', 'page' ] }
/>
)
}
```
--------------------------------
### Get a Specific Icon with useIcon
Source: https://github.com/10up/block-components/blob/develop/hooks/use-icons/readme.md
Use the `useIcon` hook to retrieve a single icon object by providing the iconSet and iconName. This hook is useful for dynamically displaying icons based on component attributes or state. Note that the `Icon` component is recommended for most use cases.
```javascript
import { useIcon } from '@10up/block-components';
function BlockEdit(props) {
const { attributes } = props;
const { iconName, iconSet } = attributes;
const icon = useIcon( iconSet, iconName );
return (
);
}
```
--------------------------------
### MediaToolbar Component Usage
Source: https://github.com/10up/block-components/blob/develop/components/media-toolbar/readme.md
Demonstrates how to integrate the MediaToolbar component into a WordPress block's edit function, including handling image selection and removal.
```APIDOC
## MediaToolbar Component
### Description
The MediaToolbar component is designed to quickly add a complete media editing experience to the `BlockControls` toolbar. It displays 'Add Image' or 'Replace Image' + 'Remove Image' buttons that manage the full media flow. The visibility of the 'Remove Image' button can be controlled via the `isOptional` prop.
### Props
| Name | Type | Default | Description |
| ---------- | ----------------- | -------- | -------------------------------------------------------------- |
| `id` | `number` | `null` | image id |
| `onSelect` | `Function` | `null` | Callback that gets called with the new image when one is selected |
| `onRemove` | `Function` | `null` | Callback that gets called when the remove image button is clicked |
| `isOptional` | `boolean` | `false` | Whether or not the Remove Image button should be shown |
| `labels` | `object` | `{}` | Custom labels prop. Used to override default labels for better UX when using different media types. Allows the sub properties `add`, `remove`, and `replace`. |
### Usage Example
```javascript
import { __ } from '@wordpress/i18n';
import { BlockControls } from '@wordpress/block-editor';
import { MediaToolbar } from '@10up/block-components';
function BlockEdit(props) {
const { attributes, setAttributes } = props;
const { imageId } = attributes;
function handleImageSelect( image ) {
setAttributes({imageId: image.id});
}
function handleImageRemove() {
setAttributes({imageId: null})
}
return (
<>
{/* ... other block content */}
>
)
}
```
```
--------------------------------
### Import and Use PostTitle Component
Source: https://github.com/10up/block-components/blob/develop/components/post-title/readme.md
Demonstrates how to import and use the PostTitle component within a React block. It shows how to specify the HTML tag and add CSS classes.
```javascript
import { PostTitle } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### Import and Use PostFeaturedImage
Source: https://github.com/10up/block-components/blob/develop/components/post-featured-image/readme.md
Demonstrates how to import and use the PostFeaturedImage component within a React block edit function. Ensure the component is imported from '@10up/block-components'.
```javascript
import { PostFeaturedImage } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### Icon Data Structure
Source: https://github.com/10up/block-components/blob/develop/stores/icons/readme.md
This is the expected structure for storing icon data within the data store.
```js
{
iconSets: {
'example/theme': {
label: 'Example',
icons: [
{
source: "...",
name: "...",
label: "..."
},
{
source: "...",
name: "...",
label: "..."
}
]
},
'core/dashicons': {
label: 'Dashicons',
icons: [
{
source: "...",
name: "...",
label: "..."
},
{
source: "...",
name: "...",
label: "..."
}
]
}
}
}
```
--------------------------------
### Basic Usage of useMaxInnerBlocks
Source: https://github.com/10up/block-components/blob/develop/hooks/use-max-inner-blocks/readme.md
Import and use the hook within your block's edit component to set a maximum number of inner blocks. Ensure you provide the parent block's clientId, the maximum allowed number, and a user-facing message.
```javascript
import { useMaxInnerBlocks } from '@10up/block-components';
import { __ } from '@wordpress/i18n';
function BlockEdit({ clientId }) {
useMaxInnerBlocks({
clientId,
max: 3,
message: __('You can only add up to 3 cards.', 'your-textdomain'),
});
return (
// ...
);
}
```
--------------------------------
### Using IconPicker Components in a Block
Source: https://github.com/10up/block-components/blob/develop/components/icon-picker/readme.md
Demonstrates how to integrate IconPicker, IconPickerToolbarButton, and InlineIconPicker into a custom block's edit function. This snippet shows attribute handling, event callbacks for icon selection, and usage within BlockControls and InspectorControls.
```javascript
import {
IconPicker,
IconPickerToolbarButton,
InlineIconPicker,
} from '@10up/block-components';
export function BlockEdit(props) {
const {
attributes,
setAttributes
} = props;
const { icon } = attributes;
const blockProps = useBlockProps();
const handleIconSelection = value => setAttributes({icon: { name: value.name, iconSet: value.iconSet }});
return (
<>
Hello World!
>
)
}
```
--------------------------------
### Basic PostMeta Usage
Source: https://github.com/10up/block-components/blob/develop/components/post-meta/readme.md
Use this snippet to display a post meta field with a specified key and an optional CSS class. The component automatically handles the display type based on the meta value.
```javascript
import { PostMeta } from '@10up/block-components';
function BlockEdit() {
return (
)
}
```
--------------------------------
### ContentSearch with Custom Fields and Results
Source: https://github.com/10up/block-components/blob/develop/components/content-search/readme.md
Shows how to customize the fields fetched from the API and normalize search results using `queryFieldsFilter` and `searchResultFilter`. This allows for more control over the data returned and how it's displayed.
```javascript
import { ContentSearch } from '@10up/block-components';
import { useCallback } from '@wordpress/element';
function MyComponent( props ) {
const queryFieldsFilter = useCallback( (fields, mode) => {
if ( mode === 'post' ) {
fields.push('excerpt');
}
return fields;
}, [] );
const searchResultFilter = useCallback( (item, result) => {
return {
...item,
url: '',
info: `ID: ${result.id} ${result.excerpt}`,
};
}, [] );
return (
{ console.log(item) } }
mode="post"
label={ "Please select a Post or Page:" }
contentTypes={ [ 'post', 'page' ] }
queryFieldsFilter={queryFieldsFilter}
searchResultFilter={searchResultFilter}
/>
)
}
```
--------------------------------
### Check Taxonomy Support with useIsSupportedTaxonomy
Source: https://github.com/10up/block-components/blob/develop/hooks/use-is-supported-taxonomy/readme.md
Import and use the hook to determine if a specific taxonomy is supported for the current post type. It returns the support status and a resolved flag for conditional rendering.
```javascript
import { useIsSupportedTaxonomy } from '@10up/block-components';
function BlockEdit(props) {
const { context } = props;
const { postType } = context;
const [isSupportingCategoryTaxonomy, hasResolvedIsSupportingCategoryTaxonomy] = useIsSupportedTaxonomy(
postType,
'category',
);
if ( ! hasResolvedIsSupportingCategoryTaxonomy ) {
return
}
return (
...
);
}
```
--------------------------------
### Using useMedia Hook in a React Component
Source: https://github.com/10up/block-components/blob/develop/hooks/use-media/readme.md
Import and utilize the useMedia hook to fetch media data within a React component. Handle the loading state by conditionally rendering a spinner before the media has resolved.
```javascript
import { useMedia } from '@10up/block-components';
function BlockEdit(props) {
const { attributes } = props;
const { imageId } = attributes;
const { media, hasResolvedMedia } = useMedia( imageId );
if ( ! hasResolvedMedia ) {
return
}
return (
);
}
```
--------------------------------
### Basic Usage of useFilteredList Hook
Source: https://github.com/10up/block-components/blob/develop/hooks/use-filtered-list/readme.md
Demonstrates how to use the useFilteredList hook to filter a list of icons based on a search term and the 'name' property. Ensure you import the necessary hooks.
```javascript
import { useIcons, useFilteredList } from '@10up/block-components';
function BlockEdit(props) {
const icons = useIcons();
const [searchTerm, setSearchTerm] = useState('');
// the useFilteredList hook only returns the icons where the value
// of the 'name' property that includes the provided search term
const [filteredIcons] = useFilteredList(icons, searchTerm, 'name');
return (
...
);
}
```
--------------------------------
### Button Block Appender Usage
Source: https://github.com/10up/block-components/blob/develop/hooks/use-render-appender-with-limit/readme.md
Shows how to use `useRenderAppenderWithLimit` with a `ButtonBlockAppender`. This is suitable for scenarios where a distinct button is desired for adding new inner blocks, and it requires specific props like `rootClientId`.
```javascript
import { useBlockProps, useInnerBlockProps, ButtonBlockAppender } from '@wordpress/block-editor';
import { useRenderAppenderWithLimit } from '@10up/block-components';
function BlockEdit(props) {
const { clientId } = props;
const renderAppender = useRenderAppenderWithLimit(4, () => );
const blockProps = useBlockProps();
const innerBlocksProps = useInnerBlockProps(
{},
{
...
renderAppender,
},
);
return (
);
}
```
--------------------------------
### Customizing ContentPicker Fields and Results
Source: https://github.com/10up/block-components/blob/develop/components/content-picker/readme.md
Shows how to customize the ContentPicker's behavior using `queryFieldsFilter`, `searchResultFilter`, and `pickedItemFilter` props. This allows for fetching specific fields, normalizing search results, and customizing the display of picked items.
```javascript
import { ContentPicker } from '@10up/block-components';
import { useCallback } from '@wordpress/element';
function MyComponent( props ) {
const queryFieldsFilter = useCallback( (fields, mode) => {
if ( mode === 'post' ) {
fields.push('excerpt');
}
return fields;
}, [] );
const searchResultFilter = useCallback( (item, result) => {
const info = `ID: ${result.id} ${result.excerpt}`;
return { ...item, url: '', info };
}, [] );
const pickedItemFilter = useCallback( (item, result) => {
const info = `ID: ${result.id} ${result.excerpt.rendered}`;
return {...item, url: '', info };
}, [] );
return (
{ console.log(pickedContent) } }
mode="post"
label={ "Please select a Post or Page:" }
contentTypes={ [ 'post', 'page' ] }
queryFieldsFilter={queryFieldsFilter}
searchResultFilter={searchResultFilter}
pickedItemFilter={pickedItemFilter}
/>
)
}
```
--------------------------------
### Custom Appender Component
Source: https://github.com/10up/block-components/blob/develop/hooks/use-render-appender-with-limit/readme.md
Illustrates using `useRenderAppenderWithLimit` with a custom React component as the appender. This allows for complete control over the appender's UI and behavior, though actual block insertion logic needs separate implementation.
```javascript
import { useBlockProps, useInnerBlockProps } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';
import { useRenderAppenderWithLimit } from '@10up/block-components';
import { __ } from '@wordpress/i18n';
// Custom appender component
function CustomAppender({ children, ...props }) {
return (
);
}
```
--------------------------------
### Using InnerBlockSlider Component
Source: https://github.com/10up/block-components/blob/develop/components/inner-block-slider/readme.md
Demonstrates how to import and use the InnerBlockSlider component in a React component. Ensure you have the correct client ID for the parent block.
```javascript
import { InnerBlockSlider } from '@10up/block-components';
const MyComponent = ({clientId}) => {
}
```
--------------------------------
### Basic Usage of useDebouncedInput
Source: https://github.com/10up/block-components/blob/develop/hooks/use-debounced-input/readme.md
Demonstrates how to integrate useDebouncedInput with SearchControl for debounced search functionality. The hook returns the debounced value, a setter function, and the current debounced value.
```javascript
import { SearchControl } from '@wordpress/components';
import { useDebouncedInput } from '@10up/block-components';
function BlockEdit(props) {
const [searchInput, setSearchString, searchString] = useDebouncedInput('');
...
async fetchTitles => {
let options = await apiFetch({
path: addQueryArgs('/wp/v2/search', {
search: searchString,
...
})
});
options = options.filter(option => option.title !== '');
return options;
};
...
return (
<>
{
setSearchString(newSearchString);
}}
/>
...
>
);
}
```
--------------------------------
### Registering Custom Icons
Source: https://github.com/10up/block-components/blob/develop/api/register-icons/readme.md
Use this snippet to register a new set of icons with a unique name and label. Each icon within the set requires its SVG source, a name, and a label.
```javascript
import { registerIcons } from '@10up/block-components';
registerIcons({
name: 'example/theme',
label: "Example",
icons: [
{
source: ''),
name: "search",
label: "Search"
},
{
source: '',
name: "edit",
label: "Edit"
},
...
]
});
```
--------------------------------
### Register Post Meta for AbstractRepeater
Source: https://github.com/10up/block-components/blob/develop/components/repeater/readme.md
Register the post meta field in PHP to support the AbstractRepeater component's data handling. Ensure the schema is correctly defined for an array of strings.
```php
register_post_meta('post', 'alternative_titles', [
'show_in_rest' => [
'schema' => [
'type' => 'array',
'items' => [
'type' => 'string'
]
]
],
'single' => true,
'type' => 'array',
'default' => []
]);
```
--------------------------------
### Default Appender Usage
Source: https://github.com/10up/block-components/blob/develop/hooks/use-render-appender-with-limit/readme.md
Demonstrates how to use the `useRenderAppenderWithLimit` hook with the default block appender. This is useful when you need to limit the number of inner blocks without customizing the appender's appearance or behavior.
```javascript
import { useBlockProps, useInnerBlockProps } from '@wordpress/block-editor';
import { useRenderAppenderWithLimit } from '@10up/block-components';
function BlockEdit() {
const renderAppender = useRenderAppenderWithLimit(4);
const blockProps = useBlockProps();
const innerBlocksProps = useInnerBlockProps(
{},
{
...
renderAppender,
},
);
return (