I am a beginner in WordPress development looking to build a block with tab navigation using <LinkControl />. I am still learning, so any guidance/materials/code examples will be appreciated.
My question is, if I have multiple <LinkControl />, how would I check the current index of that <LinkControl /> in order to set the attributes?
Here is my code in index.js:
const amountDefault = [
{
title: 'Link 1',
url: '#',
opensInNewTab: false,
id: 0,
},
{
title: 'Link 2',
url: 'https://www.google.com',
opensInNewTab: false,
id: 1,
},
{
title: 'Link 3',
url: 'https://www.amazon.co.uk',
opensInNewTab: false,
id: 2,
},
];
const blockAttributes = {
items: {
type: 'array',
default: amountDefault,
},
};
registerBlockType('my-theme/nav-bar', {
title: __('Nav bar', 'my-theme'),
icon: 'welcome-add-page',
category: 'layout',
supports: {
multiple: true,
},
attributes: blockAttrs,
and here is the code for my edit function:
const { items } = attributes;
return (
<Fragment>
<p>Test2</p>
<nav>
<ul>{listItems}</ul>
</nav>
<p>Testing Link Control</p>
{items.map((item, index) => (
<LinkControl
value={{ url: item.url, title: item.title, opensInNewTab: item.opensInNewTab }}
onChange={value => {
// create link manager for each item
// when clicking on 'edit' on item - replace the value with the new value
}}
/>
))}
I am not sure how to reference that particular item in my array in order change edit the link – could someone help me please?
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
Actually, the LinkControl index is already there in your code.. it’s in the items.map( ( item, index ) ) — yes, that index. So just use it in your onChange callback.
And presuming that your edit function starts like ( { attributes, setAttributes } ) => { ..., i.e. the setAttributes is defined, you can try the following in place of what you currently have:
items.map( ( item, index ) => (
<LinkControl
value={ { ...item } }
onChange={ ( value ) => {
// do not change the existing 'items' array; clone it instead
const newItems = [ ...items ];
// then update the one being edited
// the 'index' below is the one passed to .map() above
newItems[ index ] = { ...newItems[ index ], ...value };
// then update the block attributes
setAttributes( { items: newItems } );
console.log( value, newItems, items ); // for testing/debugging
} }
/>
) )
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