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 (
            <img src={imagePath} className='img-thumbnail rounded-circle' alt='' />

export default CustomImg

1 Answer 1


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:



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.