I'm developing a custom Gutenberg block and would like to use the same JavaScript code on frontend and backend.
In the save function of the block I generate the following html code (abridged):
return (
<div {...blockProps}>
<table className="my-plugin-table" data-rows="50">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
</table>
</div>
)
The frontend code reads the data attribute and creates the tbody element with 50 rows that are fetched from an API via fetch(), like so:
const tables = document.querySelectorAll('.my-plugin-table')
tables.forEach(table => {
const tbody = document.createElement('tbody')
table.appendChild(tbody)
const rows = table.dataset.row
const apiURL = 'https://xxxxxxx?rows=' + rows
fetch(apiRUL)
.then(response => response.json())
.then(data => {
const trs = []
data.elements.forEach(element => {
const tr = document.createElement('tr')
const td1 = document.createElement('td')
const td2 = document.createElement('td')
td1.innerHTML = element.key
td2.innerHTML = element.label
tr.replaceChildren(td1, td2)
trs.push(tr)
})
tbody.replaceChildren(trs)
})
})
In the edit function of the block I use the identical html code:
return (
<div {...blockProps}>
<table className="my-plugin-table" data-rows="50">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
</table>
</div>
)
What is the best practice here to use the frontend JavaScript in the backend as well? I need to access the dom element inside the editor. I tried it with wp.data.select( 'core/block-editor' ).getBlocks()
but to no avail.
Can you maybe give me a hint what would be the best solution in the Gutenberg and WordPress way?