DEV Community

Cover image for How do you use the `<LinkControl />` component in Gutenberg development?
Honza
Honza

Posted on • Updated on

How do you use the `<LinkControl />` component in Gutenberg development?

I'm trying to develop a custom CTA button component that will be used in all of our custom Gutenberg blocks. I'd like the authors to be able to click on the button in the editor and change the button text, URL (with option to search the existing posts/pages/CPTs/…) and set the target and rel attributes. I've been playing around with URLInputButton, URLPopover and eventually stumbled upon LinkControl, but I just can't get it to work at all. The documentation doesn't provide any example of its use either. Does anybody here knows?

// A simplified example showing what I've been trying so far…
function edit( props ) {
    const { attributes: { btnText, url }, setAttributes } = props;
    return (
        // <ButtonGroup className={`flex cta`}>
        //     {/* <Button url={`#url`}>
        //     </Button> */}
        //     <Button url={url} >
        //     <PlainText
        //         placeholder={ __(`Calling to act`, cvslug) }
        //         value={btnText || `Click`}
        //         onChange={ (newText) => setAttributes({ btnText: newText }) }
        //     />
        //     </Button>
        //     {/* <URLInputButton
        //         url={ url }
        //         onChange={ (url, post) => setAttributes( { url, btnText: (post && post.title) || `Click here` } ) }
        //     /> */}
        // </ButtonGroup>
        <LinkControl />
    );
}
Enter fullscreen mode Exit fullscreen mode

===
Photo by Matt Collamer on Unsplash

Top comments (2)

Collapse
 
filipecsweb profile image
Filipe Seabra

Have you figured this out?

Collapse
 
crs1138 profile image
Honza

Hi Felipe, sorry I have not seen your comment earlier. Short answer – no. I haven't worked out how to use <LinkControl /> I wanted.

Longer answer

I have worked out something that served my particular case. I built it a workaround by modifying the edit function of the core/button.

I made a higher order component and added a filter that replaces the default edit function for core/button.

// button/index.js
const buttonEditClone = createHigherOrderComponent((EditComponent) => {
    return (props) => {
        const { name } = props;
        if (name !== 'core/button') {
            return <EditComponent {...props} />;
        }
        return <ButtonEditComponent {...props} />;
    };
});

addFilter('editor.BlockEdit', 'my-plugin/button', buttonEditClone);
Enter fullscreen mode Exit fullscreen mode

Within the <ButtonEditComponent /> I then I constructed my own <Popover /> that is displayed when user wants to edit the options of the button. Inside of that I was able to achieve what I needed.

I hope that helps to point you in your desired direction. That is if you haven't worked it out yourself yet (and probably better) πŸ˜€ Good luck!