سؤال

I am trying to fetch profile for current login user in SharePoint 2019. But if there is no profile image then it will throw error in img tag. So I created small component that if profile image is not there than it will bring default image. But my if the image is there still it did not bring. Kindly help me.

I am passing below url while calling,

const avatar = `${webUrl}/_layouts/15/userphoto.aspx?size=L&username=${email}`
<CustomImg src={avatar} /> 

above webUrl & email are coming pageContext

import React from 'react'

const CustomImg = (props: any) => {
    let imagePath = ''
    try {
        imagePath = require(props.src)
    } catch (err) {
        imagePath = require('../assets/images/defaultAvatar.jpg')
    }
    return (
        <React.Fragment>
            <img src={imagePath} className='img-thumbnail rounded-circle' alt='' />
        </React.Fragment>
    )
}

export default CustomImg
هل كانت مفيدة؟

المحلول

I understand you want to set a default image if there is no profile image and i suspect this issue is related to SPFx webpart. If so you may take a reference of below method:

<img src={imagePath} onError={e=>{(e.target as any).src = defaultimg;}} alt='user photo'></img>

More reference:

https://stackoverflow.com/questions/38527759/how-to-check-for-broken-images-in-react-js

BR

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى sharepoint.stackexchange
scroll top