This is to separate out the building of the block and adding it to our scaffold. The front end will not be reactive yet, however it’d be nice to go ahead and add that in to the back end so we can see it in action.
Our block is going to be a little game where you press a circle, then press it again after a certain amount of time.
Making a new editor block in the scaffold
- Make a copy of a directory in src/blocks
- Rename the copied to click-game
- Remove the other block directories
- In src/blocks/click-game/block.json, fill in the new block data: the name, category and its attributes
- In src/blocks/click-game/index.js, fill in the new block settings
- In src/blocks/index.js, import our block and add it to the array and remove the others so they’re registered
- Make the block! Try to keep the components which will be used in both the editor and on the front end in one place. I’ve put them in the src/blocks/click-game/components directory.
Each click game block uses its own state to see if a user wins or loses. Yes, it could be done in vanilla js quite easily but the point of all this is not the block itself, but adding it to the front end as a React app. You’d do it the same way for a more complicated block.
This method will replace the shortcode + js method that I used to use and is far more flexible and elegant. I expect it will load quicker because we are using WordPress’s built in React package which can be cached – super helpful if we have multiple React apps.
Here’s the diff for this commit adding in the block and this is a link to the state of the repo at this point in time.