Front End JS for Blocks | WordPress Tutorial | Custom Block Development

preview_player
Показать описание
In this video, originally streamed on July 14, 2022, we look at how to load some JS on the front end of a custom Gutenberg block that only runs when the block is in view. We also learn a lot about how to use useEffect correctly and explore SWR for loading data.

00:00 Intro
01:11 Scaffold the plugin using @wordpress/create-block
07:25 Adding a viewScript property
11:00 Manually enqueueing the viewScript file in the render_callback function.
13:52 Figuring out how to know when the block is in view.
18:28 Setting up a React application for the front end of the block.
28:00 Adding an IntersectionObserver
36:39 Adding a useEffect for a counter ( and getting schooled on how useEffect works )
55:00 Adding a message prop to be displayed.
59:08 Changing opacity based on intersectionRatio.
1:02 Passing the ratio value to the component.
1:04 Do something based on when the block is in view.
1:05 Quick look at mutationObserver
1:07 Adding the Ajax call to the useEffect ( and why you shouldn’t run an Ajax call in a useEffect )
1:13 Using SWR to fetch external data instead of the useEffect.
1:19 Explaining why our bundle sizes are so small when using the @wordpress packages.

Resources:

Рекомендации по теме
Комментарии
Автор

Just dropping a note of thanks for explaining viewScript. Hours of going around in circles with webpack, et al, came to an abrupt end with one line added to block.json. Thank you!

sidewaysdesign
Автор

Hi, how can I get the block attributes in the ViewScript?

carlbengtsson
Автор

Hi Ryan, I know that I can use jQuery in view.js but I need to manualy enqueue jquery in functions.php. So I assume that it is prefered to use vanilla JS or React. Is there a wordress package like jQuery with functions like fadeIn/fadeOut or do I need to reinvent the wheel and build such functions specific for the block?

ShounenKaze
Автор

Hi Brother, Thank you so much for sharing these tips.
If it is possible can you show how to create a custom control in the Post Settings Sidebar, What I mean is before Gutenberg we can add the Custom Meta boxes to this sidebar(I know still we can add, but I think doing the Gutenenberg way will be more appropriate now). So what I need is a custom panel like "Featured Image" or "Excerpt" or "Discussion", Eg, say I want to create another panel, for showing Author Profile and add a checkbox or tggler for the post author to enable the profile under the post detail page. I hope you got my question.
Thanks in advance.

salihk