Mehdi Faraji
Mehdi Faraji

Reputation: 3816

How to load javascript cdn scripts in component instead of index.html?

I have three scripts in the index.html at the public folder :

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-zoom/1.6.1/jquery.zoom.min.js"></script>
    <script>
      $(document).ready(function () {
        $("#ex1").zoom();
      });
    </script>

And in the component I have an image which works with these scripts :

import React from "react";
import "./Home.css";

function Home() {
  return (
    <React.Fragment>
      <div class="zoom" id="ex1">
        <img
          src="https://i.pinimg.com/736x/3e/3e/49/3e3e49c8e76076f09ef1170a95b09cfb.jpg"
          class="img"
          alt="Daisy on the Ohoopee"
        />
      </div>
    </React.Fragment>
  );
}

export default Home;

I want to have all the scripts in the exact component but I don't know how .

How can I move all the scripts from the index.html at the public folder into my react component ?

Upvotes: 1

Views: 795

Answers (1)

Ako
Ako

Reputation: 1583

You can create the script dynamically:

useEffect(()=>{
   const script = document.createElement("script");    
   script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
   script.async = true;

   document.body.appendChild(script);
},[]);

but it's not recommended to load scripts inside the component.

Upvotes: 1

Related Questions