Uploading Images
Learn to upload an image for the banner area.
In this lesson, we will add the ability to add a background image in the banner area. This can be done by adding a button in the banner block’s settings, that allows the user to choose a background image. If we select the overall banner block, we want the button to appear in the right-hand sidebar that lets the user choose a background image.
Imports
As discussed before, the InspectorControls
element is responsible for displaying items in the sidebar. Open the edit.js
file from the banner folder. We need to import the following:
InspectorControls
,MediaUpload
andMediaUploadCheck
from theblock-editor
package.Button
,PanelBody
, andPanelRow
from thecomponents
package.
import { InnerBlocks, InspectorControls, MediaUpload, MediaUploadCheck } from "@wordpress/block-editor";import { Button, PanelBody, PanelRow } from "@wordpress/components";
Right now, we are returning a <div>
with a nested <InnerBlocks>
component. To return multiple items, we need to nest them inside an empty React fragment (as there can be only one root element in the return
statement). Inside the fragment, we will add the InspectorControls
component. The placement doesn’t matter. It can be added above or below the <div>
. Whatever we nest inside this component will be visible on the right-hand sidebar.
return (<><InspectorControls></InspectorControls><div className="image-and-banner"><img className="image" src={imgURL} alt="" /><div className="banner-section"><div className="banner"><InnerBlocks allowedBlocks={["excellenceblocktheme/heading", "excellenceblocktheme/button"]}/></div></div></div></>);
Panel for choosing background image
Inside the InspectorControls
, add the PanelBody
and PanelRow
components. Give it a title
prop of Background Image and set the panel to be open by default.
<InspectorControls><PanelBody title="Background Image" initialOpen={true}><PanelRow></PanelRow></PanelBody></InspectorControls>
Inside the PanelRow
, we will use the MediaUploadCheck
component to make sure that the user has permissions to upload media. The MediaUpload
component is nested inside. It is used as a self-closing component where we specify three props, on select
, value
, and render
.
<InspectorControls><PanelBody title="Background Image" initialOpen={true}><PanelRow><MediaUploadCheck><MediaUpload onSelect={} value={} render={}/></MediaUploadCheck></PanelRow></PanelBody></InspectorControls>
value
The value
prop is the ID of the media file chosen by the user. We will create an ...