2

I am trying to develop a dynamic block plugin where I store up to 7 links using Gutenberg and so far here is part of my code:

edit: props => {

  const {
    attributes: {
      links = [],
      max_links = 7
    },
    setAttributes
  } = props;

  const onChangeLink = (index, newLink) => {
    setAttributes({ links[index]: newLink });
  };

  const listItems = () => {
    var items = [];

    for(var i=1;i<max_links+1;i++) {
      items.push(
        <RichText
          placeholder={__("Link "+i, "wpblock")}
          value={links[i]}
          onChange={onChangeLink} />
      );
    }

    return items;
  };

  return [
    <div>
      <h2>Quick Links</h2>
      <ul>
        {listItems()}
      </ul>
    </div>
  ];
},

save(props) {
  return null;
}

On save I return null because I will handle this part as a callback on the php side. I saw this technique in a LinkedIn course that would allow the plugin to be modified in the future without breaking the plugin on the pages where the plugin is already being used.

My questions are:

1) How do I store the values of links so that they persist? I've seen examples but they always seem to be storing their data in posts which seems to be overkill. I have also read about WP options but I am also not sure this is the best approach in my case or if I can use it with React?

2) my onChangeLink function is not working, I am not sure how I could call it so that I pass the index of the link I want to edit?

1
  • That looks like the edit function of a GB block, but where is the save function in your block? Or is this something else? I assume this is javascript based on the JSX syntax, please edit your Q to provide more context, a lot of the context is assumed and doesn't carry over to readers, as a plugin is written in PHP, but this isn't PHP
    – Tom J Nowell
    Mar 31, 2020 at 15:12

1 Answer 1

0

The answer to my own questions is that you can't. When you create a dynamic block you depend on the server side (PHP) entirely to generate the content and then JS can rebuild from the HTML but you cannot have this occur the other way around.

So unless I create a custom table or can get the data from an API where PHP can access it before JS there is no way to achieve what I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.