I am creating a customized Gutenberg block and want to use the identical JavaScript code on frontend and backend.
Within the save perform of the block I generate the next html code (abridged):
return (
<div {...blockProps}>
<desk className="my-plugin-table" data-rows="50">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
</desk>
</div>
)
The frontend code reads the info attribute and creates the tbody factor with 50 rows which might be fetched from an API through fetch(), like so:
const tables = doc.querySelectorAll('.my-plugin-table')
tables.forEach(desk => {
const tbody = doc.createElement('tbody')
desk.appendChild(tbody)
const rows = desk.dataset.row
const apiURL = 'https://xxxxxxx?rows=" + rows
fetch(apiRUL)
.then(response => response.json())
.then(knowledge => {
const trs = []
knowledge.parts.forEach(factor => {
const tr = doc.createElement("tr')
const td1 = doc.createElement('td')
const td2 = doc.createElement('td')
td1.innerHTML = factor.key
td2.innerHTML = factor.label
tr.replaceChildren(td1, td2)
trs.push(tr)
})
tbody.replaceChildren(trs)
})
})
Within the edit perform of the block I exploit the equivalent html code:
return (
<div {...blockProps}>
<desk className="my-plugin-table" data-rows="50">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
</desk>
</div>
)
What’s the greatest observe right here to make use of the frontend JavaScript within the backend as nicely? I have to entry the dom factor contained in the editor. I attempted it with wp.knowledge.choose( 'core/block-editor' ).getBlocks()
however to no avail.
Are you able to possibly give me a touch what can be the perfect resolution within the Gutenberg and WordPress manner?