Bootstrap Carousel in SPFX (ReactJS)

Introduction

 
Bootstrap carousel is a stable carousel among the 3rd party carousels. In this article, I am using the PnpV2 library for consuming Sharepoint operations.
 
Open a command prompt and create a directory for the SPFx solution.
 
md spfx-BootstrapCarousel
 
Navigate to the above created directory.
 
cd spfx-BootstrapCarousel
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter for the default name (spfx-BootstrapCarousel in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part; i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest).
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
Selected choice - same folder.
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
Selected choice - N (install on each site explicitly).
 
Permissions to access web APIs
 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
Selected choice - N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice - WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
Selected choice - BootstrapCarousel
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice - React
 
The Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command:
 
npm shrinkwrap
 
In the command prompt, type the below command to open the solution in the code editor of your choice.
 
NPM Packages used:
  1. npm install react-bootstrap bootstrap 
  1. npm install @pnp/sp@2.0.3 --save  //for sharepoint operations  
  2. npm install @pnp/polyfill-ie11 --save  //for iell support  
Important setup
  1. protected onInit(): Promise<void> {  
  2.   
  3.   return super.onInit().then(_ => {  
  4.   
  5.     // other init code may be present  
  6.   
  7.    sp.setup({  
  8.   // set ie 11 mode  
  9.   ie11: true,  
  10.   // only needed when working within SharePoint Framework  
  11.   spfxContext: this.context  
  12. });  
  13.   });  
  14. }  
 Necessary imports
  1. import "@pnp/polyfill-ie11";    
  2. import * as React from 'react';  
  3. import "bootstrap/dist/css/bootstrap.min.css";  
  4. import Carousel from 'react-bootstrap/Carousel';  
  5. import { IBootstrapCarouselProps } from './IBootstrapCarouselProps';  
  6. import { sp } from "@pnp/sp/presets/all"
 plugin Intialisation
  1. <Carousel>  
  2.   <Carousel.Item>  
  3.     <img  
  4.       className="d-block w-100"  
  5.       src="holder.js/800x400?text=First slide&bg=373940"  
  6.       alt="First slide"  
  7.     />  
  8.     <Carousel.Caption>  
  9.       <h3>First slide label</h3>  
  10.       <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>  
  11.     </Carousel.Caption>  
  12.   </Carousel.Item><Carousel> 
Full Code
 
in BootstrapCarousel.tsx
  1. import * as React from 'react';  
  2. import "bootstrap/dist/css/bootstrap.min.css";  
  3. import Carousel from 'react-bootstrap/Carousel';  
  4. import { IBootstrapCarouselProps } from './IBootstrapCarouselProps';  
  5. import { sp } from "@pnp/sp/presets/all";  
  6. export interface Iurl {    
  7.   //File: Array<urlproperties>;    
  8.   File: urlproperties;   
  9.   MyTitle:string;  
  10.   MYDesc:string;   
  11.     
  12. }    
  13. export interface urlproperties {    
  14.   ServerRelativeUrl: string;    
  15.    
  16.      
  17. }    
  18. interface IPnpstate {      
  19.   MYPnpFile:Iurl[];    
  20. }    
  21.   
  22. export default class BootstrapCarousel extends React.Component<IBootstrapCarouselProps, IPnpstate> {  
  23.   constructor(props: IBootstrapCarouselProps, state: IPnpstate) {    
  24.     super(props);    
  25.     this.state = {    
  26.       MYPnpFile: []    
  27.     };    
  28.      
  29.   }  
  30.   public componentDidMount(){    
  31.   
  32.     this._getpnpfile()    
  33.     .then((response: Iurl[]) => {    
  34.       console.log(response);      
  35.       this.setState({ MYPnpFile: response });    
  36.     });    
  37.   }    
  38.   private _getpnpfile() {    
  39.         
  40.    /* sp.web.lists.getByTitle("PnpLibrary")  
  41.   .items.expand("Folder", "File").get()  
  42.     .then((items: any[]): void => {  
  43.     console.log(items);  
  44.     }, (error: any): void => {  
  45.   
  46.     });*/    
  47.     return sp.web.lists.getByTitle("PnpLibrary")    
  48.     .items.expand("Folder""File").top(5).get();    
  49.     
  50.        
  51.   }    
  52.   public render(): React.ReactElement<IBootstrapCarouselProps> {  
  53.     return (  
  54.       <div >  
  55.            
  56.         { this.state.MYPnpFile.length>0 && <MybootstrapCarousel bindoutput={this.state.MYPnpFile} />}  
  57.    
  58.       </div>  
  59.     );  
  60.   }  
  61. }  
  62. const MybootstrapCarousel = (props) => {    
  63.   //var abc= (document.getElementById("textBox2") as HTMLInputElement).value ;    
  64.   const Bindvalue = props.bindoutput.map((Outfile,index) =>   
  65. <Carousel.Item>  
  66.          
  67.   <img  
  68.     className="d-block w-100"  
  69.     src={Outfile.File.ServerRelativeUrl}  
  70.     alt="MY slide"  
  71.   />  
  72.   <Carousel.Caption>  
  73.     <h3>{Outfile.MyTitle}</h3>  
  74.     <p>{Outfile.MYDesc}</p>  
  75.   </Carousel.Caption>  
  76.   </Carousel.Item>  
  77.     
  78.  );    
  79.  const MAslider = (    
  80. <Carousel  interval={2000} nextIcon={<span aria-hidden="true" className="carousel-control-next-icon" />}>   
  81. {Bindvalue}   
  82. </Carousel>   
  83. );  
  84.   return (    
  85. <>  
  86.       {MAslider}</>  
  87.        
  88.    
  89.   );    
  90.  };   
Here I am using list name as PnpLibrary,MyTitle as single line of text and MYDesc as multi line of text.
 
Important Properties 
  • activeIndex - Controls the currently visible slide
  • controls - Shows the Carousel previous and next arrows for changing the current slide(Default-true)
  • fade - Cross fade slides instead of the default slide animation(Default-false)
  • indicators - Show a set of slide position indicators(Default-true)
  • interval -The amount of time to delay between automatically cycling an item. If null, carousel will not automatically cycle.(Default-5000ms)
  • keyboard - Whether the carousel should react to keyboard events.(Default-true)
  • nextIcon - Overrides the default button icon for the "next" control(eg <span aria-hidden="true" className="carousel-control-next-icon" />)
  • onSelect - Callback fired when the active item changes.(eventKey: number, event: Object | null) => void
  • onSlid - Callback fired when a slide transition ends.(eventKey: number, direction: 'left' | 'right') => void
  • onSlide - Callback fired when a slide transition starts.(eventKey: number, direction: 'left' | 'right') => void
  •  pause - If set to this, pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave. If set to false, hovering over the carousel won't pause it. (default-hover)
  • prevIcon - Override the default button icon for the "previous" control(eg.<span aria-hidden="true" className="carousel-control-prev-icon" />)
  • slide - Enables animation on the Carousel as it transitions between slides. (Default-true)
  • touch - Whether the carousel should support left/right swipe interactions on touchscreen devices. (Default-true)
Expected output
 
Bootstrap Carousel In SPFX(ReactJS)
 

Conclusion

 
We learned how to implement bootstrap carousel in SPFX. I hope this helps someone. Happy coding :)