Is there any way to dynamically get the icon of the files using its extensions in Sharepoint SPFX?
Thanks in Advance!
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It only takes a minute to sign up.
Sign up to join this communityYou can use the SP.Web.mapToIcon method to map a file name to an icon. To use it from SPFx, you would make a REST API call to /_api/web/maptoicon(filename, progid, size)
.
An example call would be /_api/web/maptoicon(filename='filename.pdf', progid='', size='0')
.
Here are some additional resources that may help you.
Getting the default document icon using Office 365 SharePoint REST API
You can use approaches like SP.Web.mapToIcon
as Rob says (as a general rule, you should always listen to what Rob says!), but if you simply want to render a file icon, you can use the PnP React Reusable Controls; There is a FileTypeIcon control which does all the hard work for you.
After you install the control in your SPFx project (using npm install @pnp/spfx-controls-react --save --save-exact
)
In your code, you need to import the control:
import { FileTypeIcon, ApplicationType, IconType, ImageSize } from "@pnp/spfx-controls-react/lib/FileTypeIcon";
And then place the controls where you'd like to display them, passing the filename as a parameter:
/* Showing the icons font */
<FileTypeIcon type={IconType.font} path="https://contoso.sharepoint.com/documents/filename.docx" />
<FileTypeIcon type={IconType.font} path="https://contoso.sharepoint.com/documents/filename.xslx" />
/* Showing the icon image */
<FileTypeIcon type={IconType.image} path="https://contoso.sharepoint.com/documents/filename.docx" />
/* Icon image allows three different sizes */
<FileTypeIcon type={IconType.image} size={ImageSize.small} application={ApplicationType.Excel} />
<FileTypeIcon type={IconType.image} size={ImageSize.medium} application={ApplicationType.Excel} />
<FileTypeIcon type={IconType.image} size={ImageSize.large} application={ApplicationType.Excel} />
For more information, take a look at https://pnp.github.io/sp-dev-fx-controls-react/controls/FileTypeIcon/
I hope this helps?