0

I am working on react project where I need to use the LinkedIn apis. I basically want to do the same as done here: https://www.c-sharpcorner.com/blogs/fetch-linkedin-data-using-javascript

However, in my project, I only work with components, I don't have control over the host page, so I can't use tags to reference the linkedin apis. What I did was this:

var script = document.createElement('script');
script.setAttribute('src','https://platform.linkedin.com/in.js');
document.head.appendChild(script);

Which actually renders the JS file for the api, however, how can I do the step mentioned in the article like this:

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
   api_key: XXXXXXX //Client ID  
   onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
   authorize: true  
</script>  

I am not sure how to translate this to React without having to change the actual host page. Can we do this on the components level?

diedu
  • 19,277
  • 4
  • 32
  • 49
M365 Dev
  • 43
  • 5

2 Answers2

0

Not sure if this will work but you could try setting the innerHTML value for the script dom object

var script = document.createElement('script');
script.setAttribute('src','https://platform.linkedin.com/in.js');
script.innerHTML = `
   api_key: XXXXXXX //Client ID  
   onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
   authorize: true  
`;
document.head.appendChild(script);
diedu
  • 19,277
  • 4
  • 32
  • 49
0

Make use of componentDidMount to attach the script or useEffect.


    import { useEffect, useState } from "react";
    
    const API_KEY = "XXXXX";
    
    export default function App() {
      const [scriptLoaded, setScriptLoaded] = useState(false);
    
      useEffect(() => {
        const script = document.createElement("script");
        script.async = true;
        script.src = "https://platform.linkedin.com/in.js";
        script.innerHTML = `
         api_key: ${API_KEY},
         onLoad: "", // Use eventListiner instead of this
         authorize: true,
        `;
        document.head.appendChild(script);
        script.addEventListener("load", () => {
          // added your logic here.
          setScriptLoaded(true);
        });
      }, []);
    
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
          {scriptLoaded
            ? "Yes!!! script has loaded"
            : "No@@@@ Script has not yet loaded"}
        </div>
      );
    }

AbhishekGowda28
  • 994
  • 8
  • 19