To retrieve the actual value from a lookup column in SPFX, you need to use the ID
of the item in the lookup column to get the corresponding item from the lookup list and then retrieve the value of the desired field from that item. Here's an example of how you can modify your code to get the actual value from the lookup column:
private _renderList(items: ISPListItem[]): void {
let html: string = '<table class="TFtable" border=1 width=100% style="border-collapse: collapse;">';
html += '<th>Title</th><th>Issuing Authority</th><th>Enforcement Status</th>';
items.forEach((item: ISPListItem) => {
html += `
<tr>
<td>${item.Title}</td>
<td>${item.Issuing_x0020_AuthorityId ? this._getLookupValue(item.Issuing_x0020_AuthorityId, "Authoritative_x0020_Documents", "Title") : ""}</td>
<td>${item.Enforcement_x0020_StatusId ? this._getLookupValue(item.Enforcement_x0020_StatusId, "Authoritative_x0020_Documents", "Title") : ""}</td>
</tr>
`;
});
html += '</table>';
const listContainer: Element = this.domElement.querySelector('#spListContainer');
listContainer.innerHTML = html;
}
private _getLookupValue(lookupId: number, listName: string, fieldName: string): string {
let lookupValue: string = "";
const endpoint: string = `${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${listName}')/items(${lookupId})?$select=${fieldName}`;
return this.context.spHttpClient.get(endpoint, SPHttpClient.configurations.v1)
.then(response => {
if (response.ok) {
return response.json();
} else {
console.log(`Error getting item with ID ${lookupId} from list ${listName}: ${response.statusText}`);
}
})
.then(data => {
if (data) {
lookupValue = data[fieldName];
}
return lookupValue;
})
.catch(error => {
console.log(`Error getting item with ID ${lookupId} from list ${listName}: ${error}`);
return lookupValue;
});
}
In the _renderList
method, we check if the lookup column has a value (item.Issuing_x0020_AuthorityId
and item.Enforcement_x0020_StatusId
) and if it does, we call the _getLookupValue
method to retrieve the actual value from the lookup list. The _getLookupValue
method constructs the REST API endpoint to get the item with the specified ID
from the lookup list and then retrieves the value of the specified field (fieldName
) from the returned item.
References: