WP DEV Section 24: Plugin Development: Blocks, Gutenberg & React


WordPress

Updated Mar 14th, 2022

Intro to JSX

createElement takes three arguments, but is rarely used because its painful to type html structure, but instead we use JSX. Makes our lives easier. Need Node and @wordpress/scripts. browser understands JS not JSX.

Link to build/index.js file.

no config just specific foldee/file structure

src folder and src/index.js file

return JSX in edit function

add build script & start script. Start watches ongoing where build is one time. WP/scripts creates build folder with transpiled non-human-readable index.js file that converts jsx to js.

tell WP to load this version in browser

index.php, admin assets, paste changed ‘build/index.js’ Refresh is now working.

auto-tab triggers with vscode settings to update files.associates to javascriptreact

only one top-level element; can use react fragment

unexpected invalid conflict issue.

Dont Want hardcoded text but text field and ability to store data

Block type attributes

need to bridge gap between editor/admin code and front-end code. attributes are this coomon ground.

adds input in jsx

attributes: {
skyColor: {type: “string”}
}

add onChange atribute to input

onChange={updateSkyColor}

this function is defined in edit

props.setAttributes({})

event parameter

props connect

neeed to tell js to use values where onChange is

attributes in html comment

could be happy with this but there is another way we wont use (Brad says he prefers to leave in comments): saved html to be source of truth by wrapping in span with className of skyColor. in attributes definition we add s souce: “text”, selector:”.skyColor”

Output of block Part 1

why we see error message in editor. WP wants to trust saved text, when we change html structure it throws things out of whack.

how to save changed html structure w/o error. tell WP their is a history. top-;evel property nmed deprecated which gets array of objects

brad doesnt like the defacto sav; function strategy. needs to manullay re-save posts?! not practical. don’t like this block where static string of text. only shown to show the wp recommneded way.

brad goes with dynamic blocks and just has save: function(props) {
return null
}

dont need deprecated property

Output of block Part 2

in index.php use different action hook.

use init instead of enqueue_editor-Assets

wp-enqueue-script to wp_register-script

the strategy described here shows how you can use php on the fly

ob_start()

drawback: extra 2 seconds but caching fixzes