Automatically change image based on breakpoint in NextJS application/XMCloud Pages editor with Tailwind css

This could be useful if you want to change image based on break point. I've cloned the existing Image component and created a ResponsiveImage component. This component is same as Image.tsx. This file uses the NextImage component and understandably doesn't have the capability to display different images based on breakpoint and that is what this note is about. Here is the original code highlighted for reference:




With that context, In the new ResponsiveImage.tsx file, i added a method named ArtDirectedImage:

//////

/////

Since a new template is created as part of cloning the Image rendering, I modified the template to accommodate the new fields in the new ResponsiveImage template as follows:


Changes on top of responsiveimage.tsx file to accommodate the new fields - MobileImage and TabletImage:

/////////

///////

Also, ensure Image is imported on top:

import Image from 'next/image'

The Default method must return this body that accommodates image change on-the-fly:

////////

///////

End-result in pages.sitecorecloud.io:


At this point, although the images change based on break point, they don't solve the actual purpose of the pages editor since the content editor wouldn't be able to edit the images there!


So, the tsx file must use the Sitecore-editor compatible JSS component when in editor mode as follows:

/////////////
///////////

Then, you have this capability to select separate images in pages editor:

while, rendering host will now toggle images based on breakpoint!

If you are a purist who wants to display only the image for the selected device in pages editor, with tailwind css, this is the code that does the trick:

//////****
//////****

If your typescipt lint doesn't like 'any', define the correct interface and use it on the props -


ResponsiveImage.tsx:
//////

Comments

Popular Posts