Search code examples
reactjsmicrosoft-graph-api

Is there an easy way to display the profile image from graph api in a react application


I am looking for an easy way to display the image response from graph api into the react application. Something like this https://blogs.aaddevsup.xyz/2020/05/how-to-get-and-display-the-user-photo-with-graph-sdk-for-net-in-a-wpf-application/

When I try I get this from the api, not sure what format the response is in and how to convert and show it as image?

enter image description here


Solution

  • MS Graph Docs - Using the binary data of the requested photo has some helpful note.

    Here is a sample component pulled from the docs. Note am using Axios to fetch the photo using responseType: 'blob' config and render it when I have it.

    I could not get it to work without that config.

    import { useEffect, useState } from 'react';
    import Axios from 'axios'
    
    function App() {
      const [imageUrl, setImageUrl] = useState(null)
      useEffect(() => {
        Axios.get('https://graph.microsoft.com/v1.0/me/photo/$value', {
          headers: { 'Authorization': 'Bearer eyJ...' },
          responseType: 'blob'
        }).then(o => {
          const url = window.URL || window.webkitURL;
          const blobUrl = url.createObjectURL(o.data);
          setImageUrl(blobUrl)
        })
      }, [])
      return (
        <div className="App">
          {imageUrl && <img alt='my-user-avatar' src={imageUrl} />}
        </div>
      );
    }
    
    export default App;
    

    FYI, you may also be interested in using MS Graph UI Toolkit for Reactjs as you seem to be rendering user profile card.