Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

How to use React cloudinary with typescript?

$
0
0
  1. I am working on a project with TypeScript and React.
  2. trying to use react cloudinary to upload an image and get the url for the image.
  3. Since the example code is in js, an error occurs if I create a file with tsx.

This is the example code I would like to use.`

    import { createContext, useEffect, useState } from "react";    // Create a context to manage the script loading state    const CloudinaryScriptContext = createContext();    function CloudinaryUploadWidget({ uwConfig, setPublicId }) {      const [loaded, setLoaded] = useState(false);      useEffect(() => {        // Check if the script is already loaded        if (!loaded) {          const uwScript = document.getElementById("uw");          if (!uwScript) {            // If not loaded, create and load the script            const script = document.createElement("script");            script.setAttribute("async", "");            script.setAttribute("id", "uw");            script.src = "https://upload-widget.cloudinary.com/global/all.js";            script.addEventListener("load", () => setLoaded(true));            document.body.appendChild(script);          } else {            // If already loaded, update the state            setLoaded(true);          }        }      }, [loaded]);      const initializeCloudinaryWidget = () => {        if (loaded) {          var myWidget = window.cloudinary.createUploadWidget(            uwConfig,            (error, result) => {              if (!error && result && result.event === "success") {                console.log("Done! Here is the image info: ", result.info);                setPublicId(result.info.public_id);              }            }          );          document.getElementById("upload_widget").addEventListener("click",            function () {              myWidget.open();            },            false          );        }      };      return (<CloudinaryScriptContext.Provider value={{ loaded }}><button            id="upload_widget"            className="cloudinary-button"            onClick={initializeCloudinaryWidget}>            Upload</button></CloudinaryScriptContext.Provider>      );    }    export default CloudinaryUploadWidget;    export { CloudinaryScriptContext };

`Example code link => https://cloudinary.com/documentation/react_image_and_video_upload

  1. Since I am not going to modify the functional part, I tried to ignore the type using any.

  2. I tried using both const and let instead of var in var myWidget on line 30.

  3. I want to use this code without type errors.

  4. I would like to use CloudinaryUploadWidget.js by changing it to CloudinaryUploadWidget.tsx.

I would appreciate your help.


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>