SPFx – Working with deep links in a Teams tab

2020-03-30

Working with SharePoint Framework in Teams a common use case is the ability to generate links to various items, so called deep links. More information on deep links can be found here. Our component will require Teams context and the webpart app id. App id is found in the webpart manifest file and teams context is found in the main webpart file:

const elemProps: IDemoTeamsDeepLinkProps = {
     teamsContext: this.context.sdks.microsoftTeams,
     appId: "d5825c47-3fa4-47bc-a571-dc3809fb90a3"
 };

Next, we define our component. It can generate a deep link and upon load it will check if a value has been passed, and if so, present it. Deep link follows the format:

https://teams.microsoft.com/l/entity/<appId>/<entityId>?context={"subEntityId":"<CUSTOMVALUE>","channelId":"<channelId>"}

The property subEntityId is where we have the possibility to pass in a custom value. This will also be the property we check when the component loads. Our complete component will look like this:

import * as React from 'react';
import {IMicrosoftTeams} from '@microsoft/sp-webpart-base';

export interface IDemoTeamsDeepLinkProps {
    teamsContext: IMicrosoftTeams;
    appId: string;
}

export const DemoTeamsDeepLink: React.FC<IDemoTeamsDeepLinkProps> = ({teamsContext, appId}) => {    
    const [itemId, setItemId] = React.useState<string>(null);
    const [deepLink, setDeepLink] = React.useState<string>(null);

    const generateDeepLink = async () => {
        const {entityId, channelId} = teamsContext.context;
        const link = encodeURI(`https://teams.microsoft.com/l/entity/${appId}/${entityId}`
            + `?context={"subEntityId":"${itemId}","channelId":"${channelId}"}`);

        setDeepLink(link);
    };

    React.useEffect(() => {
        const {subEntityId} = teamsContext.context;
        
        if (subEntityId) {
            setItemId(subEntityId);
        }
    }, []);

    return (
        <div>            
            <input type="text" defaultValue={itemId} onChange={(e) => {setItemId(e.target.value)}} />
            <button onClick={generateDeepLink} >Generate Deep Link</button>
            {deepLink && <p>{deepLink}</p>}
        </div>
    );
};

The generated link should look something like this: Result in Teams Paste it into a browser to see the result. That´s it for today, thanks for reading.