Articles about European Sharepoint Hosting Service
Posts tagged trick SharePoint 2013 Hosting Published

SharePoint 2013 Hosting – HostForLIFE :: How To Use PnP React Accordion Control In SPFx?
Feb 18th
Accordion menus and widgets are widely used on websites to manage a large amount of content and navigation lists. In this article, we will see step by step implementation of the accordion with SharePoint list.
Scenario
In this example, we will create a list called “Accordion” and in the list, we will create a Description field (it will be multiple lines of text -Rich text) and will use Title and Description field to expand and collapse.
We will use PnPJs to get list items and then will render them in the accordion form.
At the end, our output will be like this,
Let’s see the step-by-step implementation.
Implementation
- Create a list with Title and Description fields as mentioned above.
- Open a command prompt
- Move to the path where you want to create a project
- Create a project directory using:
1 |
md directory-name |
Move to the above-created directory using:
1 |
cd directory-name |
Now execute the below command to create an SPFx solution:
1 |
yo @microsoft/sharepoint |
After a successful installation, we can open a project in any source code tool. Here, I am using the VS code, so I will execute the command:
1 |
code . |
Now we will install pnpjs and pnp-spfx-controls-react as shown below:
1 2 |
npm install @pnp/sp --save npm install @pnp/spfx-controls-react --save --save-exact |
Now go to the src > webparts > webpart > components > I{webpartname}Props.ts file,
1 2 3 4 5 6 7 |
import { WebPartContext } from "@microsoft/sp-webpart-base"; export interface IPnpReactAccordionProps { description: string; listName: string; context: WebPartContext; } |
Create a file I{webpartname}State.ts inside src > webparts > webpart > components and create state interface as below,
1 2 3 4 5 6 7 8 9 10 |
interface IListItem { Id?: string; Title: string; Description: string } export interface IPnpReactAccordionState { listItems: IListItem[]; errorMessage: string; } |
Create a Service folder inside src and then in this folder create a file called SPService.ts. And in this file, we will create a service to get list items as below,
Here list name will come from the webpart property pane.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { WebPartContext } from "@microsoft/sp-webpart-base"; import { sp } from '@pnp/sp/presets/all'; export class SPService { constructor(private context: WebPartContext) { sp.setup({ spfxContext: this.context }); } public async getListItems(listName: string) { try { let listItems: any[] = await sp.web.lists.getByTitle(listName) .items .select("Id,Title,Description") .get(); return listItems; } catch (err) { Promise.reject(err); } } } |
Now move to the {webpartname}Webpart.ts. And create a list name property in property pane configuration and pass context and list name property as below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-property-pane'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import * as strings from 'PnpReactAccordionWebPartStrings'; import PnpReactAccordion from './components/PnpReactAccordion'; import { IPnpReactAccordionProps } from './components/IPnpReactAccordionProps'; export interface IPnpReactAccordionWebPartProps { description: string; listName: string; } export default class PnpReactAccordionWebPart extends BaseClientSideWebPart<IPnpReactAccordionWebPartProps> { public render(): void { const element: React.ReactElement<IPnpReactAccordionProps> = React.createElement( PnpReactAccordion, { description: this.properties.description, listName: this.properties.listName, context: this.context } ); ReactDom.render(element, this.domElement); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.BasicGroupName, groupFields: [ PropertyPaneTextField('description', { label: strings.DescriptionFieldLabel }), PropertyPaneTextField('listName', { label: strings.ListNameFieldLabel }) ] } ] } ] }; } } |
Move to the {webpartname}.tsx file and then bind the service using current context and the call service for get list items and set values in the state and render it in accordion control as below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import * as React from 'react'; import styles from './PnpReactAccordion.module.scss'; import { IPnpReactAccordionProps } from './IPnpReactAccordionProps'; import { IPnpReactAccordionState } from './IPnpReactAccordionState'; import { escape } from '@microsoft/sp-lodash-subset'; import { SPService } from '../../../Service/SPService'; import { Accordion } from "@pnp/spfx-controls-react/lib/Accordion"; export default class PnpReactAccordion extends React.Component<IPnpReactAccordionProps, IPnpReactAccordionState> { private _services: SPService = null; constructor(props: IPnpReactAccordionProps) { super(props); this.state = { listItems: [], errorMessage: '' } /** Bind service using current context */ this._services = new SPService(this.props.context); } public componentDidMount() { this.getListItems(); } /** Get items of selected list and set values in state */ private async getListItems() { if (this.props.listName) { let items = await this._services.getListItems(this.props.listName); this.setState({ listItems: items }); } else { this.setState({ errorMessage: 'Please enter the list name in property pane configuration.' }); } } public render(): React.ReactElement<IPnpReactAccordionProps> { return ( <div className={styles.pnpReactAccordion}> { //Map list items and render in accordion (this.state.listItems && this.state.listItems.length) ? this.state.listItems.map((item, index) => ( <Accordion title={item.Title} defaultCollapsed={true} className={"itemCell"} key={index}> <div className={"itemContent"}> <div className={"itemResponse"} dangerouslySetInnerHTML={{ __html: item.Description }}></div> </div> </Accordion> )) : <p>{this.state.errorMessage}</p> } </div> ); } } |
Now serve the application using the below command,
1 |
gulp serve |
Now test the webpart in SharePoint-SiteURL + /_layouts/15/workbench.aspx.
Output

SharePoint 2013 Hosting – HostForLIFE.eu :: Timer in Spfx (React)
Apr 2nd
In this article, we learn how to implement a timer in SPFx. The ‘useTimer’ is a react plugin, written using react hooks, that allows us to do timer functions in our component.
Steps
Open a command prompt and create a directory for the SPFx solution.
md spfx-ReactTimer
Navigate to the above-created directory.
cd spfx-ReactTimer
Run the Yeoman SharePoint Generator to create the solution.
yo @microsoft/sharepoint
Solution Name
Hit Enter to have a default name (spfx-ReactTimer 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 – ReactTimer
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. The 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 i use-timer//for timer function
- npm i bootstrap//for bootsrap css its optional
Necessary imports
- import { useTimer } from “use-timer”;
- import “bootstrap/dist/css/bootstrap.min.css”;//optional
Full Code
In ReactTimer.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import * as React from 'react'; import { IReactTimerProps } from './IReactTimerProps'; import "bootstrap/dist/css/bootstrap.min.css"; import {BasicTimer,DecrementalTimer,TimerWithEndTime} from './mytimer'; export default class ReactTimer extends React.Component<IReactTimerProps, {}> { public render(): React.ReactElement<IReactTimerProps> { return ( <div className="container"> <BasicTimer /> <DecrementalTimer /> <TimerWithEndTime /> </div> ); } } |
In mytimer.tsx,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
import * as React from 'react'; import { useTimer } from "use-timer"; import "bootstrap/dist/css/bootstrap.min.css"; import RunningButton from "./RunningButton"; import "./mystyle.css"; export const BasicTimer = () => { const { time, start, pause, reset, isRunning } = useTimer(); return ( <div className="card"> <h5 className="card-header">Basic timer</h5> <div className="card-body"> {isRunning ? ( <RunningButton /> ) : ( <button className="btn btn-primary" onClick={start}> Start </button> )} <button className="btn btn-primary" onClick={pause}> Pause </button> <button className="btn btn-primary" onClick={reset}> Reset </button> </div> <div className="card-footer"> Elapsed time: <strong>{time}</strong> </div> </div> ); }; export const DecrementalTimer = () => { const { time, start, pause, reset, isRunning } = useTimer({ initialTime: 100, timerType: "DECREMENTAL" }); return ( <div className="card"> <h5 className="card-header">Decremental timer</h5> <div className="card-body"> {isRunning ? ( <RunningButton /> ) : ( <button className="btn btn-primary" onClick={start}> Start </button> )} <button className="btn btn-primary" onClick={pause}> Pause </button> <button className="btn btn-primary" onClick={reset}> Reset </button> </div> <div className="card-footer"> Remaining time: <strong>{time}</strong> </div> </div> ); }; export const TimerWithEndTime = () => { const endTime = 5; const { time, start, pause, reset, isRunning } = useTimer({ endTime }); return ( <div className="card"> <h5 className="card-header">Timer with end time</h5> <div className="card-body"> {isRunning ? ( <RunningButton /> ) : ( <button className="btn btn-primary" onClick={start}> Start </button> )} <button className="btn btn-primary" onClick={pause}> Pause </button> <button className="btn btn-primary" onClick={reset}> Reset </button> </div> <div className="card-footer"> {time === endTime ? ( <span>Finished!</span> ) : ( <span> Ellapsed time: <strong>{time}</strong> </span> )} </div> </div> ); }; |
In mystyle.css:
1 2 3 4 5 6 7 8 9 10 11 |
h1, p { font-family: Lato; } button{ margin-right: 5px; } .card{ margin-bottom: 30px; } |
In RunningButton.tsx:
1 2 3 4 5 |
import * as React from 'react'; const RunningButton = () => <button className="btn btn-primary" disabled style={{ cursor: 'default'}}>Running...</button>; export default RunningButton; |
Properties
Property | Description |
endTime | the value for which timer stops |
initialTime | the starting value for the timer |
interval | the interval in milliseconds |
step | the value to add to each increment/decrement |
timerType | the choice between a value that increases (“INCREMENTAL”) or decreases (“DECREMENTAL”) |
Expected Output
Conclusion
In this post, we learned how to implement timers in SPFx. I hope this helps someone, happy coding! 🙂