SlideShare uma empresa Scribd logo
1 de 75
Custom Gutenberg Block
Development With React
@imranhsayed
Imran Sayed
What are Gutenberg
Blocks?
Gutenberg Blocks
● Every content element (e.g. heading, paragraph, or
YouTube embed) is a block.
● The collection of blocks makes up the content on the
page.
● Gutenberg is a block-based editor.
Gutenberg Blocks
Design Reuse
Editing
Experience
Ways of building Gutenberg Blocks
ES 5
ESNext &
JSX
Why write blocks in ES6/ESNext?
Arrows
Block
Scoping
Modules
Classes
Promises
ES5
ES5 ESNext
ES5 ESNext
Adding JSX
What is JSX?
Adding JSX
● JavaScript XML
● A syntax that blends HTML and JavaScript.
● Provides syntactic sugar for the React.createElement() or
wp.element.createElement() in Gutenberg.
JSX Example
Type of Component
JSX Example
Type of Component
Lowercase letter: Built in component
Capitalized: React Component
ES5 ESNext
ES5 ESNext + JSX
Why write blocks in ES6/ESNext?
Easy to Read & Write Code
Why write blocks in ES6/ESNext?
Prevents need
for globals Shorter Syntax
Functions
Why write blocks in ES6/ESNext?
● Simpler Code - Easy to read and write.
● Shorter Syntax using Arrow functions.
● Organize your code into smaller modules.
● Anticipate and prevent need of globals.
Why write blocks in ES6/ESNext?
● Block Scoping solves possible scoping ambiguity.
● Promises provide improved readability via methods
chaining and succinct error handling
Challenges
● Requires an extra build step for code transformation.
● ES5 without JSX can run straight in the browser.
● Locating and understanding the compiled source code is
difficult.
● Tooling around JavaScript could be intimidating.
Browser support
Solution
@wordpress/scripts
A collection of reusable scripts for
WordPress Development.
Features of @wordpress/scripts
● Abstracts required libraries away to standardize and
simplify development.
● Handles the dependencies and default configuration for
webpack and Babel.
● Linting tools for JavaScript and Css.
● Code testing using jest.
● Check required licence and engines.
Block Development
Build blocks in 3
steps
1.Installing Packages
Install packages with @wordpress/scripts
mkdir custom-blocks
cd custom-blocks
npm init
npm i --save-dev --save-exact @wordpress/scripts
mkdir src
touch index.php src/index.js src/editor.css src/style.css
Directory Structure
├── node_modules
├── package-lock.json
├── package.json
└── src
├── editor.css
├── style.css
└── index.js
├── index.php
Install packages with @wordpress/scripts
Entry point : src/index.js
Output: build/index.js ( enqueue this file )
Add scripts in package.json
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start"
},
npm run start
Directory structure after build
├── build
│ └── index.js
├── node_modules
├── package-lock.json
├── package.json
└── src
├── editor.css
├── index.js
└── style.css
├── index.php
2. Register Block
Server Side
Register block Server Side
add_action( 'init', 'register_block' );
function register_block() {}
Register front-end styles
public function register_block() {
// Block front end styles.
wp_register_style(
'gtcb-block-front-end-styles',
GTCB_BLOCKS_URL . '/src/style.css',
[ ],
filemtime( GTCB_BLOCKS_PATH . '/src/style.css' )
);
Register editor styles
public function register_block() {
…..
// Block editor styles.
wp_register_style(
'gtcb-block-editor-styles',
GTCB_BLOCKS_URL . '/src/editor.css',
[ 'wp-edit-blocks' ],
filemtime( GTCB_BLOCKS_PATH . '/src/editor.css' )
);
Register script
public function register_block() {
…..
// Block editor script.
wp_register_script(
'gtcb-block-editor-js',
GTCB_BLOCKS_URL . '/build/index.js',
[ 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n' ],
filemtime( GTCB_BLOCKS_PATH . '/build/index.js' ), true
);
Dependencies
● wp-blocks : includes block type registration and related
functions.
● wp-element : includes the WordPress Element abstraction for
describing the structure of your blocks.
● wp-editor : includes components like RichText, MediaUpload
etc
Register block server side
public function register_block() {
…..
// Block editor script.
register_block_type(
'gtcb-blocks/custom-blocks',
[
'style' => 'gtcb-block-front-end-styles',
'editor_style' => 'gtcb-block-editor-styles',
'editor_script' => 'gtcb-block-editor-js',
] );
3. Register Block
Client Side
Register block client side
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( 'gtcb-blocks/custom-block', { key: value } );
Block name Block configuration object
Register block client side
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( 'gtcb-blocks/custom-block', {
title: __( 'Custom Block', 'custom-blocks' ),
icon: 'megaphone',
category: 'common',
edit: () => ( <div>Hello World</div> ),
save: () => ( <div>Hello World</div> )
} );
Edit function
● Describes the structure of the block
● Represents what the editor will render when the block is
used on the editor.
edit: () => ( <div>Hello World</div> ),
Save function
● Decides how your content would look at the front end.
● Defines how the attribute will combine together to
generate a final mark up.
● Mark up then serialized and saved into the database
save: () => ( <div>Hello World</div> ),
Run the script
State of a Block
State
● A state is a plain JavaScript object.
● A state of a block is maintained through the editing
session.
● To achieve dynamic change in the block’s structure when
the user changes a block.
● Everytime a block is updated edit function is called.
Post saved in database
<!-- wp:gtcb-blocks/custom-block -->
<div class="wp-block-gtcb-blocks-custom-block" >Hello World</div>
<!-- /wp:gtcb-blocks/custom-block -->
Block name
Attributes
Attributes
● Help you extract block attribute values from saved post
content.
● Map from the saved markup to a JavaScript
representation of a block.
● Attribute sources are a superset of functionality
provided by hpq
Attributes
● hpq: A small library used to parse and query HTML
markup into an object shape.
● When you define these attributes into
registerBlockType(), it is passed to the edit() and save()
Define Attributes
registerBlockType( 'gtcb-blocks/custom-block', {
...
attributes: {
fullName: {
type: 'array',
source: 'children',
selector: 'p'
},
},
look for the text inside of selector
Attributes passed to edit() and save()
edit: ( props ) => {
console.warn( props );
return ( <div>Hello World</div> )
},
save: ( props ) => {
return ( <div>Hello World</div> )
},
Let’s console props
attributes:
fullName: []
className: "wp-block-gtcb-blocks-custom-block"
name: "gtcb-blocks/custom-block"
setAttributes: ƒ ()
Reusable Components
Reusable Components
● Instead of creating DOM nodes using createElement(),
we can encapsulate this behavior using Components.
● Hide the complexity into their self-contained units
● Many blocks share the same complex behaviors
● Reusable Components simplify implementations of your
block’s edit function
● RichText, BlockControls, AlignmentToolbar,
RichText
RichText Component
const { RichText } = wp.editor;
registerBlockType( 'gtcb-blocks/custom-block', {
….
edit: ( props ) => {
let { attributes: { fullName } , setAttributes, className } = props;
return (
<RichText
tagName="div"
placeholder={ __( 'Full Name', 'custom-blocks' ) }
value={ fullName }
onChange={ ( value ) => setAttributes( { fullName: value } ) }
className={ className }
/>
)
},
save: ( props ) => {
let { attributes: { fullName } , className } = props;
return (
<RichText.Content
tagName="div"
value={ fullName }
className={ className }
/>
)
},
registerBlockType( 'gtcb-blocks/custom-block', {
attributes: {
fullName: {
type: 'array',
source: 'children',
selector: 'div'
},
},
edit: ( props ) => {
let { attributes: { fullName } , setAttributes, className } = props;
return (
<RichText
tagName="div"
placeholder={ __( 'Full Name', 'custom-blocks' ) }
value={ fullName }
onChange={ ( value ) => setAttributes( { fullName: value } ) }
className={ className }
/>
)
},
save: ( props ) => {
let { attributes: { fullName }, className } = props;
return (
<RichText.Content
tagName="div"
value={ fullName }
className={ className }
/>
)
User enters the data:
edit ()
User saves the data:
save ()
More Ways of building Blocks
● Ahmed Awais create-guten-block
● rtCamp’s Gutenberg’s Field Middleware
Third Party Libraries
● Editor Blocks
● Gutenberg Hub
● Gutenberg Cloud
WordPress Core for
Gutenberg
Gutenberg Core
● registerBlockType() resides in
https://github.com/WordPress/gutenberg/blob/master/
packages/blocks/src/api/registration.js.
● Components core files:
https://github.com/WordPress/gutenberg/blob/master/
packages/block-editor/src/components/
Git repo
● Git repo for this example
https://github.com/imranhsayed/custom-blocks
● Gutenberg Workshop
https://github.com/imranhsayed/gutenberg-workshop
Questions?
Questions?
Imran Sayed
@imranhsayed

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

routing.pptx
routing.pptxrouting.pptx
routing.pptx
 
Event Driven Systems with Spring Boot, Spring Cloud Streams and Kafka
Event Driven Systems with Spring Boot, Spring Cloud Streams and KafkaEvent Driven Systems with Spring Boot, Spring Cloud Streams and Kafka
Event Driven Systems with Spring Boot, Spring Cloud Streams and Kafka
 
Spring batch
Spring batchSpring batch
Spring batch
 
ASP.NET MVC.
ASP.NET MVC.ASP.NET MVC.
ASP.NET MVC.
 
VueJS: The Simple Revolution
VueJS: The Simple RevolutionVueJS: The Simple Revolution
VueJS: The Simple Revolution
 
Struts2
Struts2Struts2
Struts2
 
Arinbide.v3.0
Arinbide.v3.0Arinbide.v3.0
Arinbide.v3.0
 
Getting Started with React.js
Getting Started with React.jsGetting Started with React.js
Getting Started with React.js
 
JWT-spring-boot-avancer.pdf
JWT-spring-boot-avancer.pdfJWT-spring-boot-avancer.pdf
JWT-spring-boot-avancer.pdf
 
Spring Batch
Spring BatchSpring Batch
Spring Batch
 
React render props
React render propsReact render props
React render props
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
REST API Overview with Nutanix
REST API Overview with Nutanix REST API Overview with Nutanix
REST API Overview with Nutanix
 
KAP 업종별기술세미나 13년 06월 #02
KAP 업종별기술세미나 13년 06월 #02KAP 업종별기술세미나 13년 06월 #02
KAP 업종별기술세미나 13년 06월 #02
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해
 
Oracle ADF Tutorial/Training Study Guide
Oracle ADF Tutorial/Training Study GuideOracle ADF Tutorial/Training Study Guide
Oracle ADF Tutorial/Training Study Guide
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
 

Semelhante a Custom gutenberg block development with React

Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
Andy Peterson
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 

Semelhante a Custom gutenberg block development with React (20)

Custom gutenberg block development in react
Custom gutenberg block development in reactCustom gutenberg block development in react
Custom gutenberg block development in react
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
Social Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes DemystifiedSocial Connections VI — IBM Connections Extensions and Themes Demystified
Social Connections VI — IBM Connections Extensions and Themes Demystified
 
React js
React jsReact js
React js
 
Odoo Experience 2018 - The Odoo JS Framework
Odoo Experience 2018 - The Odoo JS FrameworkOdoo Experience 2018 - The Odoo JS Framework
Odoo Experience 2018 - The Odoo JS Framework
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Improving build solutions dependency management with webpack
Improving build solutions  dependency management with webpackImproving build solutions  dependency management with webpack
Improving build solutions dependency management with webpack
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Web components - An Introduction
Web components - An IntroductionWeb components - An Introduction
Web components - An Introduction
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Your First Gutenberg Block
Your First Gutenberg BlockYour First Gutenberg Block
Your First Gutenberg Block
 
Learn react by Etietop Demas
Learn react by Etietop DemasLearn react by Etietop Demas
Learn react by Etietop Demas
 
WEBPACK
WEBPACKWEBPACK
WEBPACK
 
Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache Ant
 
[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search
 
X tag with web components - joe ssekono
X tag with web components - joe ssekonoX tag with web components - joe ssekono
X tag with web components - joe ssekono
 
The Dojo Build System
The Dojo Build SystemThe Dojo Build System
The Dojo Build System
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
reactjs-quiz..docs.pdf
reactjs-quiz..docs.pdfreactjs-quiz..docs.pdf
reactjs-quiz..docs.pdf
 
Gradle como alternativa a maven
Gradle como alternativa a mavenGradle como alternativa a maven
Gradle como alternativa a maven
 

Mais de Imran Sayed

Digging Into Gutenberg
Digging Into GutenbergDigging Into Gutenberg
Digging Into Gutenberg
Imran Sayed
 

Mais de Imran Sayed (20)

Docker with WordPress
Docker with WordPressDocker with WordPress
Docker with WordPress
 
Why Progressive Web Apps For WordPress - WordCamp Finland
Why Progressive Web Apps For WordPress - WordCamp FinlandWhy Progressive Web Apps For WordPress - WordCamp Finland
Why Progressive Web Apps For WordPress - WordCamp Finland
 
Fastest Way of Creating Gutenberg Blocks - WordCamp Rochester
Fastest Way of Creating Gutenberg Blocks - WordCamp RochesterFastest Way of Creating Gutenberg Blocks - WordCamp Rochester
Fastest Way of Creating Gutenberg Blocks - WordCamp Rochester
 
Harness The Power Of ACF For Gatsby and WordPress
Harness The Power Of ACF For Gatsby and WordPressHarness The Power Of ACF For Gatsby and WordPress
Harness The Power Of ACF For Gatsby and WordPress
 
Improving Your Debugging Skills In WordPress
Improving Your Debugging Skills In WordPressImproving Your Debugging Skills In WordPress
Improving Your Debugging Skills In WordPress
 
Build Modern Web Applications with React and WordPress
Build Modern Web Applications with React and WordPressBuild Modern Web Applications with React and WordPress
Build Modern Web Applications with React and WordPress
 
Why progressive apps for WordPress - WordSesh 2020
Why progressive apps for WordPress - WordSesh 2020Why progressive apps for WordPress - WordSesh 2020
Why progressive apps for WordPress - WordSesh 2020
 
Digging Into Gutenberg
Digging Into GutenbergDigging Into Gutenberg
Digging Into Gutenberg
 
Fastest Way Of Creating Gutenberg Blocks With Minimal JavaScript Knowledge ...
Fastest Way Of Creating  Gutenberg Blocks  With Minimal JavaScript Knowledge ...Fastest Way Of Creating  Gutenberg Blocks  With Minimal JavaScript Knowledge ...
Fastest Way Of Creating Gutenberg Blocks With Minimal JavaScript Knowledge ...
 
Why progressive web apps for word press wc-ahemdabad
Why progressive web apps for word press wc-ahemdabadWhy progressive web apps for word press wc-ahemdabad
Why progressive web apps for word press wc-ahemdabad
 
Build fast word press site in react in 30 mins with frontity
Build fast word press site in react in 30 mins   with frontityBuild fast word press site in react in 30 mins   with frontity
Build fast word press site in react in 30 mins with frontity
 
Build Fast WordPress Site With Gatsby
Build Fast WordPress Site With GatsbyBuild Fast WordPress Site With Gatsby
Build Fast WordPress Site With Gatsby
 
Why Progressive Apps For WordPress?
Why Progressive Apps For WordPress?Why Progressive Apps For WordPress?
Why Progressive Apps For WordPress?
 
Creating Gutenberg Blocks With ACF
Creating Gutenberg Blocks With ACFCreating Gutenberg Blocks With ACF
Creating Gutenberg Blocks With ACF
 
SSR with React - Connecting Next.js with WordPress
SSR with React - Connecting Next.js with WordPressSSR with React - Connecting Next.js with WordPress
SSR with React - Connecting Next.js with WordPress
 
React with WordPress : Headless CMS
React with WordPress : Headless CMSReact with WordPress : Headless CMS
React with WordPress : Headless CMS
 
React Workshop: Core concepts of react
React Workshop: Core concepts of reactReact Workshop: Core concepts of react
React Workshop: Core concepts of react
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
React workshop
React workshopReact workshop
React workshop
 
Introduction to Gutenberg- Imran Sayed
Introduction to Gutenberg- Imran SayedIntroduction to Gutenberg- Imran Sayed
Introduction to Gutenberg- Imran Sayed
 

Último

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Último (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

Custom gutenberg block development with React

  • 1. Custom Gutenberg Block Development With React @imranhsayed Imran Sayed
  • 3. Gutenberg Blocks ● Every content element (e.g. heading, paragraph, or YouTube embed) is a block. ● The collection of blocks makes up the content on the page. ● Gutenberg is a block-based editor.
  • 5. Ways of building Gutenberg Blocks ES 5 ESNext & JSX
  • 6. Why write blocks in ES6/ESNext? Arrows Block Scoping Modules Classes Promises
  • 7. ES5
  • 11. Adding JSX ● JavaScript XML ● A syntax that blends HTML and JavaScript. ● Provides syntactic sugar for the React.createElement() or wp.element.createElement() in Gutenberg.
  • 12. JSX Example Type of Component
  • 13. JSX Example Type of Component Lowercase letter: Built in component Capitalized: React Component
  • 16. Why write blocks in ES6/ESNext? Easy to Read & Write Code
  • 17. Why write blocks in ES6/ESNext? Prevents need for globals Shorter Syntax Functions
  • 18. Why write blocks in ES6/ESNext? ● Simpler Code - Easy to read and write. ● Shorter Syntax using Arrow functions. ● Organize your code into smaller modules. ● Anticipate and prevent need of globals.
  • 19. Why write blocks in ES6/ESNext? ● Block Scoping solves possible scoping ambiguity. ● Promises provide improved readability via methods chaining and succinct error handling
  • 20. Challenges ● Requires an extra build step for code transformation. ● ES5 without JSX can run straight in the browser. ● Locating and understanding the compiled source code is difficult. ● Tooling around JavaScript could be intimidating.
  • 22. Solution @wordpress/scripts A collection of reusable scripts for WordPress Development.
  • 23. Features of @wordpress/scripts ● Abstracts required libraries away to standardize and simplify development. ● Handles the dependencies and default configuration for webpack and Babel. ● Linting tools for JavaScript and Css. ● Code testing using jest. ● Check required licence and engines.
  • 25. Build blocks in 3 steps
  • 27. Install packages with @wordpress/scripts mkdir custom-blocks cd custom-blocks npm init npm i --save-dev --save-exact @wordpress/scripts mkdir src touch index.php src/index.js src/editor.css src/style.css
  • 28. Directory Structure ├── node_modules ├── package-lock.json ├── package.json └── src ├── editor.css ├── style.css └── index.js ├── index.php
  • 29. Install packages with @wordpress/scripts Entry point : src/index.js Output: build/index.js ( enqueue this file )
  • 30. Add scripts in package.json "scripts": { "build": "wp-scripts build", "start": "wp-scripts start" },
  • 32. Directory structure after build ├── build │ └── index.js ├── node_modules ├── package-lock.json ├── package.json └── src ├── editor.css ├── index.js └── style.css ├── index.php
  • 34. Register block Server Side add_action( 'init', 'register_block' ); function register_block() {}
  • 35. Register front-end styles public function register_block() { // Block front end styles. wp_register_style( 'gtcb-block-front-end-styles', GTCB_BLOCKS_URL . '/src/style.css', [ ], filemtime( GTCB_BLOCKS_PATH . '/src/style.css' ) );
  • 36. Register editor styles public function register_block() { ….. // Block editor styles. wp_register_style( 'gtcb-block-editor-styles', GTCB_BLOCKS_URL . '/src/editor.css', [ 'wp-edit-blocks' ], filemtime( GTCB_BLOCKS_PATH . '/src/editor.css' ) );
  • 37. Register script public function register_block() { ….. // Block editor script. wp_register_script( 'gtcb-block-editor-js', GTCB_BLOCKS_URL . '/build/index.js', [ 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n' ], filemtime( GTCB_BLOCKS_PATH . '/build/index.js' ), true );
  • 38. Dependencies ● wp-blocks : includes block type registration and related functions. ● wp-element : includes the WordPress Element abstraction for describing the structure of your blocks. ● wp-editor : includes components like RichText, MediaUpload etc
  • 39.
  • 40. Register block server side public function register_block() { ….. // Block editor script. register_block_type( 'gtcb-blocks/custom-blocks', [ 'style' => 'gtcb-block-front-end-styles', 'editor_style' => 'gtcb-block-editor-styles', 'editor_script' => 'gtcb-block-editor-js', ] );
  • 41.
  • 43. Register block client side const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; registerBlockType( 'gtcb-blocks/custom-block', { key: value } ); Block name Block configuration object
  • 44. Register block client side const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; registerBlockType( 'gtcb-blocks/custom-block', { title: __( 'Custom Block', 'custom-blocks' ), icon: 'megaphone', category: 'common', edit: () => ( <div>Hello World</div> ), save: () => ( <div>Hello World</div> ) } );
  • 45. Edit function ● Describes the structure of the block ● Represents what the editor will render when the block is used on the editor. edit: () => ( <div>Hello World</div> ),
  • 46. Save function ● Decides how your content would look at the front end. ● Defines how the attribute will combine together to generate a final mark up. ● Mark up then serialized and saved into the database save: () => ( <div>Hello World</div> ),
  • 48.
  • 49. State of a Block
  • 50. State ● A state is a plain JavaScript object. ● A state of a block is maintained through the editing session. ● To achieve dynamic change in the block’s structure when the user changes a block. ● Everytime a block is updated edit function is called.
  • 51. Post saved in database <!-- wp:gtcb-blocks/custom-block --> <div class="wp-block-gtcb-blocks-custom-block" >Hello World</div> <!-- /wp:gtcb-blocks/custom-block --> Block name
  • 53. Attributes ● Help you extract block attribute values from saved post content. ● Map from the saved markup to a JavaScript representation of a block. ● Attribute sources are a superset of functionality provided by hpq
  • 54. Attributes ● hpq: A small library used to parse and query HTML markup into an object shape. ● When you define these attributes into registerBlockType(), it is passed to the edit() and save()
  • 55. Define Attributes registerBlockType( 'gtcb-blocks/custom-block', { ... attributes: { fullName: { type: 'array', source: 'children', selector: 'p' }, }, look for the text inside of selector
  • 56. Attributes passed to edit() and save() edit: ( props ) => { console.warn( props ); return ( <div>Hello World</div> ) }, save: ( props ) => { return ( <div>Hello World</div> ) },
  • 57. Let’s console props attributes: fullName: [] className: "wp-block-gtcb-blocks-custom-block" name: "gtcb-blocks/custom-block" setAttributes: ƒ ()
  • 59. Reusable Components ● Instead of creating DOM nodes using createElement(), we can encapsulate this behavior using Components. ● Hide the complexity into their self-contained units ● Many blocks share the same complex behaviors ● Reusable Components simplify implementations of your block’s edit function ● RichText, BlockControls, AlignmentToolbar,
  • 61. RichText Component const { RichText } = wp.editor; registerBlockType( 'gtcb-blocks/custom-block', { ….
  • 62. edit: ( props ) => { let { attributes: { fullName } , setAttributes, className } = props; return ( <RichText tagName="div" placeholder={ __( 'Full Name', 'custom-blocks' ) } value={ fullName } onChange={ ( value ) => setAttributes( { fullName: value } ) } className={ className } /> ) },
  • 63. save: ( props ) => { let { attributes: { fullName } , className } = props; return ( <RichText.Content tagName="div" value={ fullName } className={ className } /> ) },
  • 64. registerBlockType( 'gtcb-blocks/custom-block', { attributes: { fullName: { type: 'array', source: 'children', selector: 'div' }, }, edit: ( props ) => { let { attributes: { fullName } , setAttributes, className } = props; return ( <RichText tagName="div" placeholder={ __( 'Full Name', 'custom-blocks' ) } value={ fullName } onChange={ ( value ) => setAttributes( { fullName: value } ) } className={ className } /> ) }, save: ( props ) => { let { attributes: { fullName }, className } = props; return ( <RichText.Content tagName="div" value={ fullName } className={ className } /> )
  • 65. User enters the data: edit ()
  • 66.
  • 67. User saves the data: save ()
  • 68.
  • 69. More Ways of building Blocks ● Ahmed Awais create-guten-block ● rtCamp’s Gutenberg’s Field Middleware
  • 70. Third Party Libraries ● Editor Blocks ● Gutenberg Hub ● Gutenberg Cloud
  • 72. Gutenberg Core ● registerBlockType() resides in https://github.com/WordPress/gutenberg/blob/master/ packages/blocks/src/api/registration.js. ● Components core files: https://github.com/WordPress/gutenberg/blob/master/ packages/block-editor/src/components/
  • 73. Git repo ● Git repo for this example https://github.com/imranhsayed/custom-blocks ● Gutenberg Workshop https://github.com/imranhsayed/gutenberg-workshop