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 Answer
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.