React Media LightBox - Part 2

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



A recap of the first part of react media lightbox is a simple lightbox to go around all kinds of media files like image, video and audio. It is built as a React component with custom hooks like moving to the next slide and moving to previous slide options.

In this blog, we will bring the essential features zoom control, download, fullscreen to enhance the view experience of the media items. Lightbox components provide options for captioning the media items as well. Brought all the features only with material design and there are no dependencies required for the functionalities of the media lightbox.

Adding Caption

Caption the media item to easily identify and recognize the media items while moving around the gallery of items. We will try to bring the caption underneath with white color text which fits best for the lightbox dim background. To do that, the caption key also needs to be passed in the media array.

const data = [
  {
    media: image1,
    type: "IMAGE",
    caption: "Zoom Photo Image",
  },
  {
    media: image2,
    type: "IMAGE",
    caption: "Bubble Splash Image",
  },
  {
    media: video1,
    type: "VIDEO",
    caption: "City Traffic Video",
  },
  {
    media: image3,
    type: "IMAGE",
    caption: "Splendid Nature Image"
  },
  {
    media: image4,
    type: "IMAGE",
    caption: "Wallpaper Cave",
  },
  {
    media: image5,
    type: "IMAGE",
    caption: "Spider Man Image",
  },
  {
    media: audio1,
    type: "AUDIO",
    caption: "Demo Music",
  },
];

Inside the lightbox component, while displaying media items like image, video or audio, we would display h5 elements under the media. If the caption is not given, it will nullify the html elements. 

<h5 className={classes.caption}>
         {mediaItems[ currentSlide ].caption ? mediaItems[ currentSlide ].caption : ""}
</h5>

Css styling for the caption is to have white color text justified center to the media item.

caption: {
      color: "#fff",
      marginTop: -1,
      display: "flex",
      justifyContent: "center",
},

As we are setting the media object for the lightbox component with currentIndex, so when the user moves to the next media item, currentIndex moves over the media Object array and the caption sets up according to it.

Zoom In and Zoom Out Controls

Zoom in controls are required for image and video type of media items. Zoom in helps to see the details of the image and zoom out to have a handy look of the image. Now zoomIn and zoomOut iconButtons with intuitive help of having the zoomIn and zoomOut. Materials icons are used inside the icon button to have it.

<Tooltip title="Zoom In" arrow>
     <IconButton onClick={ZoomIn} className={classes.arrowButton} size="small">
         <ZoomInIcon />
     </IconButton>
</Tooltip>
<Tooltip title="Zoom Out" arrow>
     <IconButton onClick={ZoomOut} className={classes.arrowButton} size="small">
         <ZoomOutIcon />
     </IconButton>
</Tooltip>

Stylings for all lightbox controls will be almost the same having the material icons with white color and background matching the lightbox background image.

arrowButton: {
      color: "#ffffff",
      "&:hover": {
        backgroundColor: "#808080",
      },
      //backgroundColor: "#000000",
},

ZoomIn function increases the scale of the image by 1.1 times when it is zoomed in. Likewise, the zoom out function decreases the scale of the image by 1.1 times.

const ZoomIn = () => {
    setScale(scale * 1.1);
  };
  const ZoomOut = () => {
    setScale(scale / 1.1);
};

scale state is used as part of the transform style property in the container div block.

{mediaItems[ currentSlide ].type === "IMAGE" ? (
	<div style={{ transform: `scale(${scale})` }}>
		  <img src={media} alt="Image Broken" className={classes.lightbox} />
			<h5 className={classes.caption}>
			  {mediaItems[ currentSlide ].caption 
			         ? mediaItems[ currentSlide ].caption : ""}
			</h5>
	  </div>
	   ) : mediaItems[ currentSlide ].type === "VIDEO" ? (
		<div style={{ transform: `scale(${scale})` }}>
			<video className={classes.lightbox} controls>
			  <source src={media} type="video/mp4" />
			  <source src={media} type="video/ogg" />
			</video>
			<h5 className={classes.caption}>
				   {mediaItems[ currentSlide ].caption 
				           ? mediaItems[ currentSlide ].caption : ""}
			</h5>
	    </div>
       )

   

Full screen Control

Show the whole image or video in a full screen mode.

<Tooltip title="Full Screen" arrow>
       <IconButton onClick={setToFullScreen} className={classes.arrowButton} size="small">
                <FullscreenIcon />
        </IconButton>
</Tooltip>

When setToFullScreen clicked, element reference of the media element will be made to full screen using the requestFullScreen method.

const setToFullScreen = () => {
	    const el = inputRef.current;
	    console.log(el);
	    
	    if (el.requestFullscreen) {
	      el.requestFullscreen();
	    } 
	    else if (el.msRequestFullscreen) {
	      el.msRequestFullscreen();
	    } 
	    else if (el.mozRequestFullScreen) {
	      el.mozRequestFullScreen();
	    } 
	    else if (el.webkitRequestFullscreen) {
	      el.webkitRequestFullscreen();
	    }
  };

Input reference will be taken from the media container, then use the input reference for the requestfullscreen which will provide the full screen mode and pressing esc will land back to the lightbox mode. 

const inputRef = useRef();

<div style={{ display: "contents" }} ref={inputRef}>

Download Control

Downlaod the media items from the gallery will have similar material icon button with the tooltip items. Download control is enclosed with anchor tag so by clicking will download the media items as it suffixed with download attribute. Also anchor tag has the downloadMediaUrl state, it is to fetch the remote media item and make the media as blob url to the anchor tag.  

<a href={downloadMediaUrl} download>
        <Tooltip title="Download" arrow>
               <IconButton className={classes.arrowButton} size="small">
                        <DownloadIcon />
                 </IconButton>
        </Tooltip>
</a>

Fetch the remote media item and get the blob content to create the blob object url. Then it is set to download media url state variable which is re-rendered on the anchor tag href link.

fetch(mediaUrl).then(res => res.blob()).then(data => {
      const blobUrl = URL.createObjectURL(data);
      setDownloadMediaUrl(blobUrl);
 });

The above logic will be done when we open, moving the next media item and moving to the previous media item so that the download media blob url will be set accordingly in the download media control.

Share Control

Share control will help us to share the media item. This icon button will be added to the media control array. 

<Tooltip title="Share" arrow>
          <IconButton onClick={Share} className={classes.arrowButton} size="small">
                      <ShareIcon />
            </IconButton>
</Tooltip>

On click of the media share control, the handler opens the navigator share control. Navigator api opens up the native share window for sharing in email or get the link to it. 

const Share = () => {
    if (navigator.share) {
      navigator.share({
        title: 'Media Share',
        url: media
      }).then(() => {
        console.log('Thanks for sharing!');
      })
        .catch(console.error);
    }
  }

Few of the media controls are specific to the media type. Like zoom in, out, full screen are not applicable for audio items. So we will have an isScalable state variable based on that media controls will be conditionally rendered.


{ isScalable ? 
	<div> 
	   <Tooltip title="Zoom In" arrow>
			<IconButton onClick={ZoomIn} 
			               className={classes.arrowButton} size="small">
				<ZoomInIcon />
			 </IconButton>
	  </Tooltip>
	 <Tooltip title="Zoom Out" arrow>
	  <IconButton onClick={ZoomOut} 
	                 className={classes.arrowButton} size="small">
			<ZoomOutIcon />
	  </IconButton>
	</Tooltip>
	<Tooltip title="Full Screen" arrow>
	  <IconButton onClick={setToFullScreen} 
	                 className={classes.arrowButton} size="small">
		   <FullscreenIcon />
	  </IconButton>
	</Tooltip> </div>
  : null
 }

isScalable state variable will be set based on the media type as video or image. The condition check will be done on the first lightbox show up and the same will be done in the previous and next gallery items chosen.


if (mediaItems[ currentSlide ].type === "VIDEO" 
       || mediaItems[ currentSlide ].type === "IMAGE") 
   {
      setIsScalable(true);
   } 
   else {
     setIsScalable(false);
}
 

Complete lightbox component with the app built on top of the component is made as a workable demo and it is available in the github project. In the workable demo, we have passed remote media items, but it will work with the local media items as well. Lightbox works with all the controls like zoom, download, share options.

Github Reference: https://github.com/devgroves/reactmedialightgallery


   

DevGroves Technologies is a IT consulting and services start-up company which is predominately to web technologies catering to static website, workflow based CRM websites, e-commerce websites and reporting websites tailoring to the customer needs. We also support open source community by writing blogs about how, why and where it need to be used for.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

React Media Lightbox

  • lightbox gallery react audio video

Lightbox is a popular and widely used concept for showing the gallery of media files. It is a very impressive approach for the end user to glance through media files. Media files like audio or video will load the html audio or video controls.

Read More


Build Simple Ecommerce site using React and Jotai

  • ecommerce react jotai

Retail Ecommerce website can be created quickly with React. It can be created using React, Bootstrap, React DOM and Jotai. Data flow within the commerce site is done using Jotai in a light-weight manner. The main workflow of showing all the items in the gallery to user and user adding to the cart will be done as part of this blog.

Read More


Glific - Open Source Two Way Communication Platform for Social Sector Organizations

  • glific elixir communication architecture social-sector

Glific is an open source two way communication platform with primary focus on helping social sector organizations to interact with millions of beneficiaries concurrently through automated messages with rich media content and manual intervention wherever required. With Glific one can design flows to automate conversations, see how each of the beneficiaries is interacting with the bot and measure engagement.

Read More


A Quick Guide to Finding Open Source Social Media Management Software

  • social-media social-media-management smm

As the social media trend continues to alter the face and infrastructure of the business world as we once knew it, the need to keep up with the demand for content management is at an all-time high. Companies are putting more and more energy and resources into this area in the form of Social Media Managers and Media Communications Representatives. This can get expensive and overwhelming, so finding resources that can help alleviate some of those responsibilities is in the best interest of individuals and companies alike.

Read More


Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More



React Patent Clause Licensing issue. Is it something to worry?

  • react react-license facebook

React libraries from Facebook is one of the most used UI libraries. It is competitive to AngularJS. There are many open source UI components or frameworks available but mostly people narrow down to two choices Angular / React. Recently Facebook has updated React license and added a patent clause which makes companies to worry and rethink whether to use React or not.

Read More


React Window - Optimized way to display large list

  • react react-window large-list

In Web development, there will be always a need to display content in a large list. Rendering a large list will slow down the web page load and increase the First Contentful Paint(FCP). Usually large lists are displayed in a paginated grid where user has to move around pages by clicking next. It will be good user experience, if the same page provides data of large list as and when we scroll.

Read More


React JS Developer Salary Overview

  • reactjs javascript salary

These days, web development is a need for any business - it attracts huge investments and can kick-start businesses. As for the tools mainly used for development, JavaScript is riding the wave right now. StackOverflow has been naming it the most popular programming language for six years straight. React, as one of the most popular JS libraries is also the first choice for interface developers. It offers some of the best web development tools for mobile and single-page applications.

Read More


SeoToaster: easy, fast and efficient open source CMS for top SEO performance

  • cms content-management-system seo ecommerce

SeoToaster is a free Open Source CMS & Ecommerce solution to build, manage and market websites optimized for for top search engine performance. As the name implies, Seo Toaster is to date the only content management system (CMS) to truly integrate SEO execution and web marketing automation technology in full compliance with the search engines industry’s best practices.

Read More


Enhancing The Experience With Android TV: Briefly About One Developer's Impressions

  • android android-tv

In my software development career, I have always been attracted to new technologies and innovative solutions. Project by project, I have been exploring something new, discovering and implementing different approaches and trying new solutions. When Android TV showed up, I set a new personal goal. I described my impressions and the overall opinion on the application development for Android TV right here. Hope you will find it useful and interesting.

Read More


React Reduce Vs Jotai

  • jottai react redux

While developing web applications, we built many components and having a data model across the application wide model will be difficult. We need common store management to update and get information across all the components. In React based Web UI, redux is the official centralized state management to be used which is internally wired as state changes to the component. There are other alternatives to redux which are light-weight and simple to use. One among them is Jotai, a minimalistic API for state management. In this blog we will take one of the redux examples given in the redux site and do the same in Jotai for deeper understanding.

Read More


Top 15 Open source alternative to Microsoft products

  • microsoft-alternative open-source-enterprise

Microsoft is monopoly in the commercial software. Here are 15 best alternatives to most popular and widely used Microsoft products.

Read More


Scene.js - Library to Create Timeline-Based Animation

  • scenejs css timeline javascript animation motion

Scene.js is a JavaScript timeline-based animation library for creating animation websites. As an animated timeline library, it allows you to create a chronological order of movements and positions of objects.

Read More


10 Free services for your Website / Blog. Just plug it.

  • free website blog free-service free-resources

Each website / blog delivers useful content or service to its users. But website themselves requires some service to monitor and increase its presence. Here are few free services which could be used by Website / Blog. This will be very much helpful for small business owners.

Read More


Web based commenting system. Embed directly in to your site

  • comment free commenting-system

Comments are very important for a blog or website to get feedback from their users. Comments could be threaded where users could be discuss and post reply to the comment. Here we going discuss about the most popular and widely used free commenting system. You need to embed their javascript code in your every page and it will take care the rest of the task.

Read More


Understanding Web Real-Time Communication (WebRTC)

  • webrtc communication web

Web Real-Time Communication (WebRTC) is an open source project currently being developed with an aim to provide real time, peer-to-peer communication between web applications. WebRTC provides simple JavaScript APIs that help developers to easily build web applications with real time audio, video and data transfer capabilities. This blog has been written assuming that the reader has zero knowledge of how WebRTC works and hence have explained the entire working in detail using simple terms and analogies wherever possible. Let’s get started!

Read More


AbanteCart - Easy to use open source e-commerce platform, helps selling online

  • e-commerce ecommerce cart php

AbanteCart is a free, open source shopping cart that was built by developers with a passion for free and accessible software. Founded in 2010 (launched in 2011), the platform is coded in PHP and supports MySQL. AbanteCart’s easy to use admin and basic layout management tool make this open source solution both easy to use and customizable, depending on the skills of the user. AbanteCart is very user-friendly, it is entirely possible for a user with little to no coding experience to set up and use this cart. If the user would be limited to the themes and features available in base AbanteCart, there is a marketplace where third-party extensions or plugins come to the rescue.

Read More


Univention Corporate Server - An open source identity management system

  • ucs identity-management-system

Univention Corporate Server is an open source identity management system, an IT infrastructure and device management solution and an extensible platform with a store-like App Center that includes tested third party applications and further UCS components: This is what Univention combines in their main product Univention Corporate Server, a Debian GNU/Linux based enterprise distribution. This article provides you the overview of Univention Corporate Server, its feature and installation.

Read More


An introduction to MongoDB

  • mongodb database document-oriented-databse no-sql c++ data-mining

MongoDB is the most exciting SQL-free database currently available in the market. The new kid on the block, called MongoDB is a scalable, high-performance, open source, schema free and document oriented database that focuses on the ideas of NoSQL Approach. Written in C++, it has taken rapid strides since its emergence into the public sphere as a popular way to build your database applications.

Read More


Marketing stratigies required to sell open source product

  • opensource selling promote

Many new products are coming in the open source world. Few are forking existing project, adding new features to it and selling it as open source product. Few strategies required to follow to sell the product better.

Read More







We have large collection of open source products. Follow the tags from Tag Cloud >>


Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.