As we already see about SharePoint client side webpart creation. Now will have a look about getting list items using this. Create the client side webpart first. Click here for the steps.
Open the client side webpart in Visual Studio Code. We can able to see all the needed folder over there.
Open the client side webpart in Visual Studio Code. We can able to see all the needed folder over there.
src section is having all files about the webpart. We need to write the logic in tsx file which is under component folder.
We have a render method in that file which is used to display the content. SPFx will give the default content with welcome message. We can remove this and add our content.
Getting List Items
We may use REST API to get content from list. Will see about the steps for SPFx. Create a componentDidMount() method. We have to place our code in this method only. Before that create constructor for initializing the state.
Now create componentDidMount() method. We may use axios to call REST API. We have to install this using npm. npm command is:
npm install axios --save
import this in header of the tsx file.
import axios from 'axios';
Place the below code in the method:
var items = [];
var apiPath = "/_api/web/lists/getByTitle('listName')/items";
axios.get(apiPath).then(result => {
for (var i = 0; i < result.data.value.length; i++) {
items.push({
title: String(result.data.value[i]["Title"]),
desc: result.data.value[i]["Description"] != null ? String(result.data.value[i]["Description"]) : ""
});
}
this.setState({ listItems: items });
}
The value has been assigned to listItems state. Next we have to render this. Place the below code in render section.
return (
<div>
{
this.state.listItems.map((lItems, index) => {
return (
<div className="divVehicleContent">
<h1>{lItems.title}</h1>
<div dangerouslySetInnerHTML={{__html: lItems.desc}}></div>
</div>
);
})
}
</div>
);
That's all compile this using gulp command. Run this code in SharePoint site workbench.
Thank you very much for your post. I've been working in React and SPFX for a few months now and I'm finding almost no consistent examples online. Your post was quick and to the point... and worked.
ReplyDelete