This post is more of a note where I follow an iterative approach to build the correct code for my requirement. So, read it till the end instead of pulling out code from middle and finding you are on the wrong side!
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!
In the Tailwind CSS world, this is the simple code that should produce breakpoint-based result,
/////
////
With that background, If you are a purist who wants to display only the image for the selected device in Sitecore pages editor, with tailwind css, this is the code that does the trick:
//////****
//////****
If your typescript lint doesn't like 'any', define the correct interface and use it on the props -
Now, at this point, it dawned on me that i needed to implement aspect ratio for different device images. So, I went back and created data template fields for each device and used a drop list to list the different aspect ratios with source field pointing to a shared location.
Shared source location:
Back in tw css, I added reference to tw aspect ratio plugin - require("@tailwindcss/aspect-ratio")
then, added css style classes for different aspect ratios.
///////////
/////////?
So, all i had to do in the tsx file was to dynamically pick the respective css class name for the specific device based on aspect ratio selected in the data source.
Final code that is responsive both in the browser and XMC pages editor:
ResponsiveImage.tsx:
//////
Comments
Post a Comment