Question

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?

Was it helpful?

Solution

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
        } }
    />
) )
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top