Insights React in SharePoint

React in SharePoint

Lately I’ve been playing with ReactJS, and was looking for a way to render content in SharePoint using React. I really like React because you can easily create interactive UIs declaratively. You design simple views for each state in your application, and React will efficiently update and render the correct components when your data changes. I decided to build a lightweight YouTube client with instantaneous search, that can be referenced within any SharePoint page. This could be useful for a SharePoint help or self service site.

Source code on Github -> https://github.com/zavier-sanders/instant-youtube

Demo -> https://zavier-sanders.github.io/instant-youtube/

Getting Started

There are a few ways you can use React in SharePoint. One possible way is via the new SharePoint Framework (SPFx), which enables full support for client-side development and open source tools. I decided not to use the SPFx because it’s still in developer preview and cannot be used in Production environments yet. Another method of using React with SharePoint (which I chose) is to simply upload your javascript files to a SharePoint Document Library, and add a reference to your app using a content editor web part.

To use this example, clone this repo, install dependencies, and then start the gulp process with the following:
git clone git@github.com:zavier-sanders/instant-youtube.git
cd instant-youtube
npm install
npm start
 

In order to deploy this to SharePoint, make sure you edit the package.json file. Change the homepage setting to reflect the path to your application.


“homepage”: “/sites/developer/SiteAssets/instant-youtube”


Then build a copy to deploy to SharePoint:
npm run build  


Once the build completes, then copy the files in the build folder to the SharePoint Site Assets library. Place a Content Editor Web Part onto a page and reference the index.html file.

Example: /sites/developer/SiteAssets/instant-youtube/index.html

The Code

Within  /src/index.js  we have the following code with comments.

A brief explanation of the code:

  • In the App react component, we define the videos array and selected video as a state in the constructor.
  • We define API_KEY as a constant. Make sure to replace this key with your own key from Google. Google has documentation on how to obtain a key.
  • We execute a call to the Youtube search API in the videoSearch function, passing in a search term.
  • In the render method, we throttle our api called to 300 milliseconds. We also add the SearchBar, VideoDetail, and VideoList components. We pass in props for each component.

Conclusion

This is a simple lightweight example of using React with SharePoint. You can easily add more functionality to the app or have a particular set of help/selfservice videos loaded on initial page load.