Last active
September 7, 2023 03:20
-
-
Save wallawe/15103355b20b0b21be9ea8198c3aac96 to your computer and use it in GitHub Desktop.
Cloudinary v2 image uploader component in React (using Next.js)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 })} | |
</> | |
) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
</> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ok