SlideShare a Scribd company logo
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

More Related Content

What's hot

5 things you didn't know nginx could do
5 things you didn't know nginx could do5 things you didn't know nginx could do
5 things you didn't know nginx could do
sarahnovotny
 
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games ConferenceKGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
Xionglong Jin
 
Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2
YEONG-CHEON YOU
 
Online game server on Akka.NET (NDC2016)
Online game server on Akka.NET (NDC2016)Online game server on Akka.NET (NDC2016)
Online game server on Akka.NET (NDC2016)
Esun Kim
 
쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기
Brian Hong
 
스마트폰 온라인 게임에서 고려해야 할 것들
스마트폰 온라인 게임에서 고려해야 할 것들스마트폰 온라인 게임에서 고려해야 할 것들
스마트폰 온라인 게임에서 고려해야 할 것들
Hyunjik Bae
 
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012devCAT Studio, NEXON
 
NoSQL 위에서 MMORPG 개발하기
NoSQL 위에서 MMORPG 개발하기NoSQL 위에서 MMORPG 개발하기
NoSQL 위에서 MMORPG 개발하기
Hoyoung Choi
 
jemalloc 세미나
jemalloc 세미나jemalloc 세미나
jemalloc 세미나
Jang Hoon
 
KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직
KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직
KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직
Hyunjik Bae
 
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
Mydbops
 
Cassandra Consistency: Tradeoffs and Limitations
Cassandra Consistency: Tradeoffs and LimitationsCassandra Consistency: Tradeoffs and Limitations
Cassandra Consistency: Tradeoffs and Limitations
Panagiotis Papadopoulos
 
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
Seungmo Koo
 
VMware ESXi - Intel and Qlogic NIC throughput difference v0.6
VMware ESXi - Intel and Qlogic NIC throughput difference v0.6VMware ESXi - Intel and Qlogic NIC throughput difference v0.6
VMware ESXi - Intel and Qlogic NIC throughput difference v0.6
David Pasek
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
Amazon Web Services Korea
 
Systems Monitoring with Prometheus (Devops Ireland April 2015)
Systems Monitoring with Prometheus (Devops Ireland April 2015)Systems Monitoring with Prometheus (Devops Ireland April 2015)
Systems Monitoring with Prometheus (Devops Ireland April 2015)
Brian Brazil
 
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Esun Kim
 
Iocp advanced
Iocp advancedIocp advanced
Iocp advanced
Nam Hyeonuk
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
Joshua Zhu
 
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
DongMin Choi
 

What's hot (20)

5 things you didn't know nginx could do
5 things you didn't know nginx could do5 things you didn't know nginx could do
5 things you didn't know nginx could do
 
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games ConferenceKGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
 
Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2
 
Online game server on Akka.NET (NDC2016)
Online game server on Akka.NET (NDC2016)Online game server on Akka.NET (NDC2016)
Online game server on Akka.NET (NDC2016)
 
쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기쿠키런 1년, 서버개발 분투기
쿠키런 1년, 서버개발 분투기
 
스마트폰 온라인 게임에서 고려해야 할 것들
스마트폰 온라인 게임에서 고려해야 할 것들스마트폰 온라인 게임에서 고려해야 할 것들
스마트폰 온라인 게임에서 고려해야 할 것들
 
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
양승명, 다음 세대 크로스플랫폼 MMORPG 아키텍처, NDC2012
 
NoSQL 위에서 MMORPG 개발하기
NoSQL 위에서 MMORPG 개발하기NoSQL 위에서 MMORPG 개발하기
NoSQL 위에서 MMORPG 개발하기
 
jemalloc 세미나
jemalloc 세미나jemalloc 세미나
jemalloc 세미나
 
KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직
KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직
KGC 2014: 클라이언트 개발자를 위한 컴퓨터 네트워크 기초 배현직
 
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
PostgreSQL 15 and its Major Features -(Aakash M - Mydbops) - Mydbops Opensour...
 
Cassandra Consistency: Tradeoffs and Limitations
Cassandra Consistency: Tradeoffs and LimitationsCassandra Consistency: Tradeoffs and Limitations
Cassandra Consistency: Tradeoffs and Limitations
 
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
게임서버프로그래밍 #0 - TCP 및 이벤트 통지모델
 
VMware ESXi - Intel and Qlogic NIC throughput difference v0.6
VMware ESXi - Intel and Qlogic NIC throughput difference v0.6VMware ESXi - Intel and Qlogic NIC throughput difference v0.6
VMware ESXi - Intel and Qlogic NIC throughput difference v0.6
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
 
Systems Monitoring with Prometheus (Devops Ireland April 2015)
Systems Monitoring with Prometheus (Devops Ireland April 2015)Systems Monitoring with Prometheus (Devops Ireland April 2015)
Systems Monitoring with Prometheus (Devops Ireland April 2015)
 
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
Akka.NET 으로 만드는 온라인 게임 서버 (NDC2016)
 
Iocp advanced
Iocp advancedIocp advanced
Iocp advanced
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
 
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
[NDC 2018] 신입 개발자가 알아야 할 윈도우 메모리릭 디버깅
 

Similar to Custom gutenberg block development with React

Custom gutenberg block development in react
Custom gutenberg block development in reactCustom gutenberg block development in react
Custom gutenberg block development in react
Imran Sayed
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
Ioan Eugen Stan
 
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
Claudio Procida
 
React js
React jsReact js
React js
Rajesh Kolla
 
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
ElínAnna Jónasdóttir
 
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]
GDSC UofT Mississauga
 
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
NodeXperts
 
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 bigAndy Peterson
 
Web components - An Introduction
Web components - An IntroductionWeb components - An Introduction
Web components - An Introduction
cherukumilli2
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
LINAGORA
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
Your First Gutenberg Block
Your First Gutenberg BlockYour First Gutenberg Block
Your First Gutenberg Block
Yoav Farhi
 
Learn react by Etietop Demas
Learn react by Etietop DemasLearn react by Etietop Demas
Learn react by Etietop Demas
Etietop Demas
 
WEBPACK
WEBPACKWEBPACK
WEBPACK
home
 
Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache Ant
Shih-Hsiang Lin
 
[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search
indeedeng
 
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
Joseph Ssekono
 
The Dojo Build System
The Dojo Build SystemThe Dojo Build System
The Dojo Build System
klipstein
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
Mike Wilcox
 
reactjs-quiz..docs.pdf
reactjs-quiz..docs.pdfreactjs-quiz..docs.pdf
reactjs-quiz..docs.pdf
AyanSarkar78
 

Similar to 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
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
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
 

More from Imran Sayed

Docker with WordPress
Docker with WordPressDocker with WordPress
Docker with WordPress
Imran Sayed
 
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
Imran Sayed
 
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
Imran Sayed
 
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
Imran Sayed
 
Improving Your Debugging Skills In WordPress
Improving Your Debugging Skills In WordPressImproving Your Debugging Skills In WordPress
Improving Your Debugging Skills In WordPress
Imran Sayed
 
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
Imran Sayed
 
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
Imran Sayed
 
Digging Into Gutenberg
Digging Into GutenbergDigging Into Gutenberg
Digging Into Gutenberg
Imran Sayed
 
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 ...
Imran Sayed
 
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
Imran Sayed
 
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
Imran Sayed
 
Build Fast WordPress Site With Gatsby
Build Fast WordPress Site With GatsbyBuild Fast WordPress Site With Gatsby
Build Fast WordPress Site With Gatsby
Imran Sayed
 
Why Progressive Apps For WordPress?
Why Progressive Apps For WordPress?Why Progressive Apps For WordPress?
Why Progressive Apps For WordPress?
Imran Sayed
 
Creating Gutenberg Blocks With ACF
Creating Gutenberg Blocks With ACFCreating Gutenberg Blocks With ACF
Creating Gutenberg Blocks With ACF
Imran Sayed
 
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
Imran Sayed
 
React with WordPress : Headless CMS
React with WordPress : Headless CMSReact with WordPress : Headless CMS
React with WordPress : Headless CMS
Imran Sayed
 
React Workshop: Core concepts of react
React Workshop: Core concepts of reactReact Workshop: Core concepts of react
React Workshop: Core concepts of react
Imran Sayed
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
Imran Sayed
 
React workshop
React workshopReact workshop
React workshop
Imran Sayed
 
Introduction to Gutenberg- Imran Sayed
Introduction to Gutenberg- Imran SayedIntroduction to Gutenberg- Imran Sayed
Introduction to Gutenberg- Imran Sayed
Imran Sayed
 

More from 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
 

Recently uploaded

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 

Recently uploaded (20)

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 

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