thedeepponkiya
thedeepponkiya

Reputation: 112

How to add data to SharePoint list with SPFx using React Functional component?

I have created an SPFx React solution with the Class components and performed CRUD operations with the SharePoint list.

I have used @pnp/sp for SharePoint API calls.

Now, I need to perform CRUD operations in the SPFx React solution with the Functional components.

Can anyone suggest useful links for the same?

Thanks

Upvotes: 0

Views: 1539

Answers (1)

devil_inside
devil_inside

Reputation: 450

Its the same in Functional components.

import * as React from 'react';
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import { SPFI } from '@pnp/sp';

const SimpleFunctionComponent:React.FunctionComponent<{sp: SPFI}> = ({sp}) => {

    const [ items, setItems ] = React.useState<string[]>([]);

    React.useEffect(() => {

        const init = async () => {
            const items: any[] = await sp.web.lists.getByTitle("Test").items();
            setItems(items.map(i => i["Title"]));
        };

        if(sp) {
            init();
        }   
    }, [sp]);

    return <div>
        {
            items.map(i => <div>{i}</div>)
        }
    </div>
}

export { SimpleFunctionComponent }

You have the SPFI property (you can define and init it in the webpart.ts file). Then in the component itself you can have an useEffect hook to load items for example. The hook I use in the example will load everytime the "sp" property is changing. The result will look like this:

enter image description here

Upvotes: 1

Related Questions