The issue
I am looking for a way to add linking functionality to a custom block of mine and found different approaches to this need.
There are:
- The URLInputButton Component
- The URLInput Component
- The LinkControl Component
- The URLPopover Component
I got it somehow working with the first two components:
const {URLInputButton, URLInput, URLPopover} = wp.blockEditor;
registerBlockType('my-plugin-domain/textlink', {
title: __('Text Link', 'my-textdomain'),
...
attributes: {
url: {
type: 'string',
},
},
edit(props) {
const {
attributes,
setAttributes,
} = props;
const {url} = attributes;
const blockControls = (
!!isSelected && (
<BlockControls>
<Toolbar>
<URLInputButton
url={url}
onChange={(url, post) => setAttributes(
{url, title: (post && post.title) || __('Click here')},
)}
/>
<URLInput
className={className}
value={url}
onChange={(url, post) => setAttributes(
{url, text: (post && post.title) || 'Click here'})}
/>
</Toolbar>
}
...
});
Unfortunately the URLInput as well as the URLInputButton appear displaced/buggy when entering a link.
Hence I’m trying to figure out a way how to use the LinkControl Component and I can’t get it to work. I wasn’t even able to figure out from which Package it has to be imported yet.
const {LinkControl} = wp.blockEditor; // This doesn't seem to work
const {LinkControl} = wp.components; // Neither this
...
// This is not working:
edit(props){
...
<LinkControl
onChange={(nextValue) => {
console.log(nextValue);
}}
/>
...
}
...
Also I wasn’t able to get the URLPopover to work.
If anyone could point me into the right direction, it would be highly appreciated!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
LinkControl is an experimental component, so it’s declared differently in blockEditor package
try this as an import statement, this worked for me:
const {__experimentalLinkControl } = wp.blockEditor;
const LinkControl = __experimentalLinkControl;
Method 2
Follow up on @fluoriteen answer: you can use aliased destructured variable assignment to have an one line assignment:
const {__experimentalLinkControl: LinkControl} = wp.blockEditor;
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0