SPFx with React: A Guide to React and SPFx Integration

spx with react a guide to react and spfx integration

Introduction

Dynamic user interfaces are essential in today’s web development. React is a JavaScript library that Facebook maintains that has gained popularity for its efficiency, reusability, and simplicity. The combination of SPFx with React enables developers to produce responsive and dynamic web elements, increasing the possibilities for developing effective SharePoint solutions.

Why Choose React and SPFx?

SharePoint Framework provides a modern and flexible framework for building solutions within SharePoint. On the other hand, React simplifies UI development with its component-based structure. When used in combination they offer a powerful toolkit for developers promoting code reusability, and enhancing the user experience.

Getting Started with React and SPFx

Step 1. Set Up Your Development Environment

Before you start, ensure that Node.js and Yeoman are installed on your machine. These tools are essential for creating and managing SPFx projects. Open your terminal and execute the following commands

				
					# Install Yeoman and gulp globally
npm install -g yo gulp
# Install the SharePoint generator
npm install -g @microsoft/generator-sharepoint

				
			

Step 2. Run the following command to scaffold a new SPFx project

				
					yo @microsoft/sharepoint
				
			

After running this command, you will be prompted to provide essential details such as the project name, description, and the type of web part you wish to create. Choose the React framework option when prompted. Yeoman will then generate all the necessary project files and folder structures for your SharePoint Framework (SPFx) solution.

Step 3: Trusting the Self-Signed Developer Certificate

After scaffolding an SPFx project, it is important to establish a secure connection between the development environment and SharePoint. This can be done by trusting the self-signed developer certificate that comes with SPFx projects. Once you have created a project with the Yeoman generator for the SharePoint Framework, you need to execute the following command from the root folder of the project.

				
					gulp trust-dev-cert
				
			

Step 4: Build Your React Components

When working on SPFx with react projects, it’s best to create React components within the “src” directory. To keep things organized, you can create a “web parts” folder within the “src” directory, where you can group your components based on the specific web parts they belong to. To get started, navigate to the “src/webparts” directory in your newly created project. Here, you’ll find a folder for your web part, named after it (for example, “helloWorld”). Within this folder, there’s a file called “HelloWorld.tsx”, which contains a basic React component. You can customize this component or create new ones to suit your project’s specific requirements.

You typically start with a default class component which serves as the backbone of your SharePoint web part. However, you can increase simplicity and efficiency by converting it into a functional component.

Default class component Code

				
					import * as React from 'react';
import styles from './Helloworld.module.scss';
import { IHelloworldProps } from './IHelloworldProps';
import { escape } from '@microsoft/sp-lodash-subset';

export default class Helloworld extends React.Component<IHelloworldProps, {}> {
  public render(): React.ReactElement<IHelloworldProps> {
    const {
      description,
      isDarkTheme,
      environmentMessage,
      hasTeamsContext,
      userDisplayName
    } = this.props;

    return (
      <section className={`${styles.helloworld}`}>
        <div className={styles.welcome}>
          <h2>Well done, {escape(userDisplayName)}!</h2>
          <div>{environmentMessage}</div>
          <div>Web part property value:{escape(description)}</div>
          <h3>Welcome to SharePoint Framework!</h3>        
        </div>      
      </section>
    );
  }
}

				
			

In React, functional components are a concise and modern way to define UI elements. If the default class component in your SharePoint project seems heavy, you can opt for a functional component instead.

Converted functional Component:

				
					import * as React from 'react';
import styles from './Helloworld.module.scss';
import { IHelloworldProps } from './IHelloworldProps ';
import { escape } from '@microsoft/sp-lodash-subset';

const Helloworld: React.FC<IHelloworldProps > = (props) => {
  return (
    <section className={`${styles.helloworld}`}>
      <div className={styles.welcome}>
        <h2>Well done, {escape(userDisplayName)}!</h2>
        <div>{environmentMessage}</div>
        <div>Web part property value:{escape(description)}</div>
        <h3>Welcome to SharePoint Framework!</h3>        
      </div>      
    </section>
  );
};
export default Helloworld;

				
			

Step 5: SharePoint REST APIs

Once your React component is built, it’s time to integrate SharePoint data to improve its usefulness. Giving your web components data-driven and dynamic functionality. The REST APIs that SharePoint offers are rich enough to let you work with lists, libraries, and other SharePoint entities to execute CRUD (Create, Read, Update, Delete) actions. Here’s how to integrate SharePoint REST APIs into your React components to improve their functionality.

Make sure to install the @microsoft/sp-http package before starting. It contains the client-side libraries required to send HTTP requests.

				
					npm install @microsoft/sp-http --save
				
			

Once the necessary package has been installed, you can call SharePoint REST APIs asynchronously by using the HttpClient. To make HTTP queries, import the required dependencies, such as HttpClient, SPHttpClient from @microsoft/sp-http and React.

				
					import * as React from 'react';
import { HttpClient, SPHttpClient } from '@microsoft/sp-http';

				
			

Define the component’s props and state using TypeScript. Adjust the types according to your specific requirements

				
					interface IListDataProps {
  context: any; // Adjust the type as per your requirements
}
const ComponentName: React.FC<IListDataProps > = ({ context }) => {
  const [yourData, setYourData] = React.useState<any[]>([]);

				
			

Utilize the useEffect and useState hooks to make SharePoint REST API calls and manage the component’s state

				
					const loadListData = async (): Promise<void> => {
 try {
  const apiUrl: string = `${context.pageContext.web.absoluteUrl}/_api/web
  /lists/getByTitle('YourList')/items`;
  const response = await context.httpClient
  .get(apiUrl, SPHttpClient.configurations.v1);

  if (response.ok) {
    const data = await response.json();
    setYourData(data);
  } else {
    console.log('Failed to fetch data from SharePoint. Error:'
    ,response.statusText);
    }
  } catch (error) {
     console.log('Error loading data from SharePoint:', error);
    }
};

React.useEffect(() => {
  loadListData();
}, []); // Run once when the component mounts
				
			

Integrate the retrieved data into your functional component’s JSX

				
					 // ... rest of your component
  return (
    <div>
      {/* Your component JSX using the 'yourData' state */}
    </div>
  );
};
export default ComponentName;

				
			

Step 6: Test Locally and Debug

Run the following command to launch the local workbench and test your functional component locally

				
					gulp serve
				
			

Navigate to the provided local workbench URL in your browser (usually http://localhost:4321/temp/workbench.html) add your web part, and ensure it functions as expected. Use the browser’s developer tools and Visual Studio Code for effective debugging.

Step 7: Build and Package for Deployment

Once thoroughly tested, execute the following commands to bundle and package your solution for deployment

				
					gulp build
gulp bundle --ship
gulp bundle --debug
gulp package-solution --ship
				
			

Upload the generated .sppkg file to your app catalog in SharePoint to deploy your functional component

Conclusion

In this post, we looked at how SPFx with React can be seamlessly integrated, allowing you to create responsive and dynamic web elements. Everything from setting your environment to integrating SharePoint REST APIs into a functional component has been covered. These tools allow you to take your SharePoint projects to the next level and allow your creativity to thrive in the dynamic realm of web development by leveraging the power of React and SPFx.

Leave a Comment

Your email address will not be published. Required fields are marked *

Recent Posts

what is salesforce service cloud and how can it help your business
What is Salesforce Service Cloud and how can it help your business?
salesforce manufacturing cloud integration for the seamless sales process
Salesforce Manufacturing Cloud Integration for the Seamless Sales Process
top 5 benefits of using salesforce for high tech industry infographic
Top 5 Benefits of using Salesforce for High-Tech Industry
salesforce world tour essentials dubai
Salesforce World Tour Essentials Dubai | May 16, 2024
simplifying npl the magic of natural language processing
Simplifying NLP: The Magic of Natural Language Processing
Scroll to Top