In the previous article, I created a block that allows uploading multiple images using the MediaUpload component. This block is displaying uploaded images as it is on the frontend. You might want to add a carousel for these images. In this tutorial, I’ll show you how to add a Slick Carousel in your custom block.

Here, I am taking a Slick just for demo purposes. In your case, you might be using another carousel. The flow will be the same for any carousel. All you need to know is how to include assets of the package and initiate the carousel in a custom block.

Getting Started

Let’s first quickly scaffold our Gutenberg block and use some code from the previous article. It’ll be saved us from repeating already explained stuff. I’d recommend going through the article as well for a better understanding. After writing the code from the previous block, I’ll continue with the integration of a Slick Carousel.

Run the below command from your wp-content/plugins directory.

npx @wordpress/create-block artisansweb-carousel --variant=dynamic

This command will install the dynamic block. It might take some time to process. Upon completion, activate this plugin.

After this, add the attributes to the src/block.json file. This attribute will store the attachment ids of the uploaded images.

{
    ...
    "attributes": {
   		"images": {
			"type": "array",
			"default": []
   	 	}
    }
}

Next, using the MediaComponent we allow the user to upload multiple images into your block. The working of this component is already described in the linked article. So add the below JSX code directly into the src/edit.js file.

import { useBlockProps, MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { Button, Spinner, BaseControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';

export default function Edit({ attributes, setAttributes }) {
	const { mediaIds, medias } = useSelect( select => {
		const medias = [];
		attributes.images.forEach( (id) => {
			const img = select('core').getMedia(id);
			if ( img ) {
				medias.push(img)
			}
		});
		return {
			mediaIds: attributes.images,
			medias: medias
		}
	}, [attributes.images] )

	return (
		<div { ...useBlockProps() }>
			<BaseControl label={__("Artisans Web - Slick Carousel")}>
				<MediaUploadCheck>
					<MediaUpload
						onSelect={ ( media ) =>
							setAttributes( { images: media.map(image => image.id) } )
						}
						multiple={true}
						allowedTypes={ ['image'] }
						value={ attributes.images }
						render={ ( { open } ) => (
							<div>
								{ mediaIds.length > 0 && medias.length == 0 && <Spinner /> }
								{ !! medias && medias &&
									medias.map( image => 
										<div className="image-container">
											<img src={ image.source_url } /> 
											<Button onClick={ () => setAttributes( { images: attributes.images.filter(function(item){return item !== image.id}) } ) } isLink isDestructive>
												Remove image
											</Button>
										</div>
									)
								}
								<Button variant="secondary" onClick={ open }>Add images</Button>
							</div>
						) }
					/>
				</MediaUploadCheck>
			</BaseControl>
		</div>
	);
}

Next, this block requires some styling on the backend part. Use the below code into the src/editor.scss file.

.wp-block-create-block-artisansweb-carousel {
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	
	// Adjust the margin and width as per your requirement
	margin: 20px;
	
	.image-container {
	  	position: relative;
	  	margin: 10px;
		float: left;
	  
	  	img {
			display: block;
			width: 200px; // Adjust the image width as per your requirement
			height: auto;
	  	}
	  
	  	button {
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			margin-top: 10px;
	  	}
	}
}

At this moment, your backend is ready and you’re able to upload images to your block. Optionally, you can also remove the images.

Install Slick Carousel into Gutenberg Block

To integrate a Slick Carousel into the Gutenberg block, you need to install its package via the npm command below.

npm install slick-carousel --save

Your block should already have src/view.js file. From this file, we’ll call the Slick Carousel on the HTML element.

The reference of view.js should be defined inside the block.json as follows.

"viewScript": "file:./view.js"

This statement enqueued the view.js on the frontend when viewing the content of your block.

Here, I am using the npm package. Alternatively, you can also pass the script handle registered with wp_register_script() function.

"viewScript": ["script-handle"]

But, I’d recommend going with the npm module as it’s a better approach. You don’t need to keep your package’s asset somewhere else and register it.

Next, we also have to include slick.scss file. For this. open the src/style.scss and add the below statement on top of it.

@import "slick-carousel/slick/slick.scss";

The compiler(npm start command) merge the code from slick.scss and src/style.scss into the style-index.scss. This file you can see under the build directory. All your code written for the block is executed from this build folder.

Initialize Slick Carousel

We’re done with all the stuff required to integrate a Slick Carousel. You’ve added multiple images on the backend. Let’s display these images on the frontend and call the Slick Carousel.

src/render.php

<div <?php echo get_block_wrapper_attributes(); ?>>
    <div class="artisansweb-carousel">
        <?php
        foreach( $attributes['images'] as $image ) :
            echo wp_get_attachment_image($image, 'medium');
        endforeach;
        ?>
    </div>
</div>

Here I added the class artisanweb-carousel to the main div container. Using this selector, I’ll initialize the Slick from the view.js file.

import "slick-carousel";

jQuery(function($) {
    $('.artisansweb-carousel').slick({
        autoplay: true,
        arrows: false,
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1,
        dots: true
    });
});

Done! Now your Slick Carousel should look like the screenshot below.

slick-carousel

The post How to Build Carousel Block for Gutenberg appeared first on Artisans Web.