Download presentation
Presentation is loading. Please wait.
Published byQuentin Shields Modified over 7 years ago
1
Building Client Side Web Parts with the SharePoint Framework
How many developers do we have? Who has worked with SPFx so far? This is a developer heavy topic and presentation
2
Presented by Travis Lingenfelder Founder & Principal Consultant
About Me Professional Building web parts since 2005 and WSS v2 SharePoint roles: Solution Architect Consultant Administrator Developer Done everything from records management to dot-com sites SharePoint development team configuration manager – automated build and deploy Migrations SharePoint On-prem, SharePoint Online Azure development Office 365 Personal Married with 2 awesome kids Amateur astronomer Guitar player Enjoy the outdoors: hiking & camping Presented by Travis Lingenfelder Founder & Principal Consultant LinkedIn:
3
Then and Now… If you’ve been developing in SharePoint for a while:
Lots of C# & full trust solutions Extending from Base web part class Another web part Package, retract, deploy, & wait – IIS recycle Different world – c# in SP is kind of bad thing Front end web development stack is rapidly becoming king Tradein in: C# -> javascript Visual Studio -> Visual Studio Code Large Development VMs with 16 GB RAM -> lightweight systems – w/o SharePoint
4
Evolution of JavaScript
Old-school JavaScript Object-Oriented Modules JSON Syntax <script type="text/javascript"> function foo(bar) { alert(bar); } foo("hello world"); </script> var MODULE = (function () { var my = {}, privateVariable = 1; function privateMethod() { // ... } my.moduleProperty = 1; my.moduleMethod = function () { }; return my; }()); MODULE.moduleMethod(); var JSONModule = { "myProperty": 1, "myMethod" : function() { // ... } }; JSONModule.myMethod("hello world"); Old-school JavaScript Familiar Back in the day Create a function Call whenever its needed What we are used to Object-oriented(ish) Modules Benefit = stop pollution of the global namespace Prevent unrelated code sharing global variables Self-contained – separation of concern Better maintainability Promotes re-use Uses anonymous, self-executing functions JSON Syntax Notation for easily declaring a JavaScript object Often used for serializing data
5
Enter TypeScript Use TypeScript with The SharePoint Framework
JavaScript transpiles to ⇒ class Greeter { constructor(public greeting: string) { } public greet(): string { return "<h1>" + this.greeting + "</h1>"; } }; var greeter = new Greeter("Hello, world!"); document.body.innerHTML = greeter.greet(); var Greeter = (function () { function Greeter(greeting) { this.greeting = greeting; } Greeter.prototype.greet = function () { return "<h1>" + this.greeting + "</h1>"; }; return Greeter; }()); var greeter = new Greeter("Hello, world!"); document.body.innerHTML = greeter.greet(); TypeScript Bridges the gap between strongly-typed, object oriented languages and loosely-typed, prototyping language of JavaScript TypeScript = a superset of JavaScript that transpiles (compiles) to plain JavaScript Uses strongly-typed declaration files of your objects tsd is the old standard to get definitely-typed declarations for common libraries Now a retired project @types is the new standard and is used with npm
6
The Rest of the Tool Chain
Visual Studio Code ≅ ≅ File → New Project ≅ ≅ New tools Funny names Yeoman Gulp Perform familiar functions to things we already know [CLICK] NodeJS server-side JavaScript runtime environment Event-driven I/O Node.JS Command Prompt Get used to the command prompt Basically replaces Menus GUI tools Similar to Visual Studio, File -> New Project Project scaffolding New project wizard Creates project structure and artifacts Scaffolding created depends on the Yeoman generator used Specific generator for SPFx projects Npm Package manager Get external libraries & dependencies Visual Studio Code Lightweight IDE Really powerful text editor SPFx tooling is not in full blown version of VS yet Great intellisense for all things JavaScript Task runner Performs a series of steps (tasks) Transpilie typescript Bundle with webpack Launch web server Like hitting F5 Connect Lightweight web server Used to host the local SP workbench IIS ≅ ≅ Connect http server
7
Building a Promoted Links Client-Side Web Part
Promoted Links Demo
8
Demo 1 Promoted Links in SharePoint Show Promoted links Tiles List
Modern pages are missing web parts for many (most) classic web parts We will rebuild the promoted links web part Show data from existing promoted links list Make it available on a modern page Promoted Links in SharePoint
9
Setup Your Dev Environment
Downloads Visual Studio Code - Node JS LTS version (4.x.x) - NPM Commands (Node.js Command Prompt) npm -g install npm install --global --production windows-build-tools npm i -g yo gulp npm i -g @latest gets the latest version can also be used to get a specific version
10
Create a Web Part Project
To create a project Open the Node.js command prompt Create a new folder to host your project Call the Yeoman generator for sharepoint Answer a few questions WAIT – may take a while When done you should get the Congratulations screen Open the project: code .
11
Your Project Is Ready Review project structure Config
Solution packaging and deployment details Node_modules Like the Visual Studio packages folder Dependencies included with the generator or added using npm Exclude from source control Automatically if using git Extremely large 100 MB or more Just the nature of modern web development Common complaint for noobs Src Where your code lives Web parts Typings Older style typescript declarations You can now start developing But there is one thing you should consider doing first
12
Run ≅ gulp serve To avoid this warning in the future, run: gulp trust-dev-cert Equivalent of F5 is gulp serve May get a security warning – trust it New gulp task to install a developer certificate on your machine SharePoint workbench mock of a modern SharePoint page NOT SharePoint Single webpage Looks like SharePoint
13
Demo 2 Web Part Project Template Demo1 folder Show Gulp serve
Show workbench Add hello world web part Open property pane Edit text Show device previews Web Part Project Template
14
Source Control ≅ Git QUICK SIDE NOTE ABOUT SOURCE CONTROL
Always use source control Personal project – use source control Company project – use source control Doesn’t have to cost you anything TFS Online free for 5 users Github.com May have noticed everyone is using git now Even the Windows OS source is now hosted in a git repo TFS Online allows us to use TFVC or Git Easy to select when creating a new team project For your reference, I have included the steps For TFS Online Git repo Not going to go over it in detail just Follow the commands highlighted in yellow to get started
15
Building a Promoted Links Client-Side Web Part
16
What is React? JavaScript UI library from Facebook
Instagram.com written entirely in React Virtual DOM Renders subtrees of nodes based upon state changes When changes are applied 1) performs a “diff” to identify what has changed 2) reconciliation to update the DOM based on the diff Don’t manipulate React elements with jQuery! Component rendering using JSX (JavaScript XML syntax transform) Who has used REACT? UI library from Facebook Instagram.com written entirely in React Web developers should be familiar with the DOM Probably used jQuery to manipulate DOM items REACT has a virtual DOM Tracks information about REACT Elements Uses a differencing engine to determine UI updates Don’t manipulate REACT elements with jQuery JSX – XML syntax for Elements
17
Anatomy of a React Component
props – properties passed to a React component state – component status used when rendering this display Lifecycle Methods render() – process the virtual DOM and update the display getInitialState() – initial state value getDefaultProps() – fallback for when props are not supplied setState(state) – triggers UI updates componentWillMount() – Invoked once, on both client & server before rendering occurs. componentDidMount() – Invoked once, only on the client, after rendering occurs. LOAD DATA HERE shouldComponentUpdate() – Return value determines whether component should update. componentWillUnmount() – Invoked prior to unmounting component. Every REACT component has: Properties State Properties are passed into the component on creation State contains the current state or settings of the REACT Element Not going to go over each one of these Render – process the virtual DOM to update the display setState – make changes to the state and trigger the render method. Do not set the state property manually Always use the setState method Only exception is when setting the state in the constructor For promoted links Moving the mouse over the tile Mouse over event sets the component to the hover state Mouse out event sets it to the normal state componentDidMount – logic to load data i.e. query SharePoint data Only invoked once Don’t get data in the render method Render is called each time the virtual DOM is reprocessed May make a lot of unnecessary web service calls
18
Thinking in React Split UI into multiple components – a component should do only one thing Build in phases – start with a static version and add functionality Do not set state directly – use setState() Split UI into multiple components a component should do only one thing Separation of concerns Example A React component that has 2 other react components 1 provides search 1 is the list of goods Then broken down into 2 more components Heading component Item component Each only does 1 thing Promoted link web part 2 react components List component in red Item component in blue Work in React Build in phases Build something static and simple Get layout and styles right Add on functionality 1st – show static elements Then – go and get data Then – add additional functionaly
19
SharePoint Framework Client Side Web Part
Import other JavaScript modules import default from ‘path’; import { nonDefault } from ‘path’; import default, { nonDefault } from ‘path’; Import * as moduleName from ‘path’; Pay attention to this import Define a class and mark it as the default export. Extends BaseClientSideWebPart. Creates an instance of a React component in render() Screen shots made in a developer preview version of the SPFx Code is under source Webparts Folder for the specific web part in the project SPFx artifacts REACT artifacts are in the components folder PromotedLinksWebPart.ts Create a class that derives from the BaseClientSideWebPart Similar to how web derived from the WebPart class in c# Imports are like using statements Instead of the entire namespace like a c# using statement Specify the components that you want to use Several examples Show web part class as default export for module Show importing the module default From is a relative path from the current file Non-default components go in curley braces Can import an entire module and assign it to a name Current item is not a REACT component This is a basic SharePoint framework web part We import the react component Instantiate the react component Pass properties Define the web part property pane: pages, groups, controls
20
React Component The exports for the previously mentioned import statement. Creates a new class based from a React.Component. Define props and state types. JSX. Not your standard HTML element. i.e. use of className, not class (TypeScript reserved word). Use { } to access JavaScript object values
21
Create a new file/React component to be used for each Promoted Link Item
We will use an Office UI Fabric React component for displaying the images. Define the props that will be used for this component. Define a class for the new component and mark it as the default export. Extends React.Component<propsType, stateType> Create a new file in the components folder.
22
Office UI Fabric http://dev.office.com/fabric
Microsoft library of UI styles & components Similar to Bootstrap and FontAwesome Styles Icons Colors Typography Responsive grid Large array of UI components for use across Office, SharePoint, and Other applications Multiple versions Fabric Core Fabric React Fabric JS Fabric AngularJS Fabric iOS
23
Establish basic rendering for the PromotedLinkItem component
Don’t forget to export objects you will use in other components. Office UI Fabric Image component. Supply IImageProps values. Use props when rendering the component Use JSX to define the rendering for the component
24
Add instances of the PromotedLinkItem to the parent PromotedLinks component
Import the PromotedLinkItem component and property types Create static items while performing initial testing and applying styles
25
SharePoint Workbench running on localhost
≅ F5 (Run)
26
Demo 3 Basic Rendering
27
Non-Conflicting Styles
28
Now it is starting to look like a Promoted Links web part
Let’s Add Some Style Now it is starting to look like a Promoted Links web part
29
Sass (Syntactically Awesome StyleSheets)
CSS extension Allows for the use of: Variables Calculations Imports Mixins etc. Nested rules for organization Transpiles to normal CSS
30
SASS Style Sheet Variable for use in other styles Using the variable in multiple styles Use the variable in calculations
31
Demo 4 Sass Styles With Real-Time Compile and Refresh
32
Git – now is a good time to save changes to source control
commit sync
33
Add Hover State Show a description panel when the mouse hovers over an item. Remember to use setState() calls render(). Tip: .bind(this) provides context of the React component, not the HTML element in events.
34
Register the state type for use with the component
Define the component state type Set the initial state. Ok to directly set state here. Event handlers to manipulate the state. Use setState to trigger render(). Can use JSON for setting simple values. Register the events on an element. Use .bind(this) to ensure the component context from within event handler, not the hovered HTML element. Change rendering according to current state. In this case swap CSS class names.
36
Demo 5 Hover Interaction
37
Working With SharePoint Data
Promoted Links list in classic SharePoint Promoted Links Client Side Web Part
38
Initialize the state with an empty array
Use componentDidMount() lifecycle method to get data If working in a local workbench set the state with mock data. Note: collapsed for brevity. Tip: Use ` for strings with embedded variables. If NOT in a local workbench query SharePoint for items in the list configured in the listId property. For each query result, add a new item to the array Easy request method from Waldek Mastykarz. See resources slide for link. Make sure to setState
39
For each item in the state array, create a new PromotedLinkItem
Brackets indicate a JavaScript block
40
Demo 6 Complete Solution
41
References Get the code, slide deck, or watch the presentation video
react-and-the-office-ui-fabric Other Tutorials and References Learning React - Basics of Git - Easy-to-use Request method for SharePoint (Waldek Mastykarz) - sharepoint-framework-client-side-web-parts-react/ Dynamic drop-downs in web part properties - framework-spfx-web-part-properties-dynamic-dropdown.html
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.