Skip to content

Instantly share code, notes, and snippets.

@wallawe
Last active September 7, 2023 03:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wallawe/15103355b20b0b21be9ea8198c3aac96 to your computer and use it in GitHub Desktop.
Save wallawe/15103355b20b0b21be9ea8198c3aac96 to your computer and use it in GitHub Desktop.
Cloudinary v2 image uploader component in React (using Next.js)
import { Component } from 'react'
import Head from 'next/head'
const CLOUD_NAME = '<name here>'
export default class ImageUploader extends Component {
constructor(props) {
super(props)
this.uploader = null
}
static defaultProps = {
preset: '<preset default>',
}
componentDidMount() {
const {preset, callback} = this.props
if (!this.uploader) {
this.uploader = window.cloudinary.createUploadWidget(
{
cloudName: CLOUD_NAME,
uploadPreset: preset,
},
(error, result) => {
if (!error && result && result.event === 'success') {
callback(result.info)
}
}
)
}
}
open = () => {
this.uploader.open()
}
render() {
return (
<>
<Head>
// this is Next.js specific, but if you're using something like Create React App,
// you could download the script in componentDidMount using this method: https://stackoverflow.com/a/34425083/1424568
<script
src="https://widget.cloudinary.com/v2.0/global/all.js"
type="text/javascript"
/>
</Head>
{this.props.children({ open: this.open })}
</>
)
}
}
import ImageUploader from 'components/image_upload_cloudinary'
import axios from 'axios'
const Cards = () => {
const saveImage = async (data) => {
// if you need to do something with the data you get back from cloudinary
// e.g. save the publicId in your database
await axios.post('/url', data)
}
return (
<>
<h3>Upload an Image</h3>
<ImageUploader callback={saveImage}>
{({ open }) => <button onClick={open}>Upload files</button>}
</ImageUploader>
</>
)
}
@frayhan94
Copy link

ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment