Skip to content

Instantly share code, notes, and snippets.

@cosio55 cosio55/ImageField.jsx
Last active Jun 24, 2019

Embed
What would you like to do?
This gist is an example on how to create an image field for the uniforms library on Meteor. Also using Simple Schema, React Drop Zone (with preview), and uploading the images into Cloudinary.
import React, { useEffect, useState } from 'react';
import connectField from 'uniforms/connectField';
import { useDropzone } from 'react-dropzone';
import { Cloudinary } from 'meteor/socialize:cloudinary';
const ImageField = ({ onChange, value, ...props }) => {
const [files, setFiles] = useState([]);
const { getRootProps, getInputProps } = useDropzone({
accept: 'image/*',
multiple: false,
noDrag: true,
onDrop: (acceptedFiles) => {
setFiles(
acceptedFiles.map(file => Object.assign(file, {
preview: URL.createObjectURL(file),
})),
);
const reader = new FileReader();
reader.readAsDataURL(acceptedFiles[0]);
reader.onload = () => {
if (reader.result) {
const logo = Cloudinary.uploadFile(reader.result);
logo.then((val) => {
const { url, public_id } = val;
onChange({
url,
public_id,
});
});
}
};
},
});
const thumbs = files.map(file => (
<div key={file.name}>
<div>
<img src={file.preview} />
</div>
</div>
));
useEffect(
() => () => {
files.forEach(file => URL.revokeObjectURL(file.preview));
},
[files],
);
const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
return (
<div className="field form-group">
<label className="control-label">{capitalizeFirstLetter(props.name)}</label>
<div {...getRootProps({ className: 'dropzone' })}>
<input {...getInputProps()} />
<p>Drag 'n' drop some files here, or click to select files</p>
</div>
<aside>{thumbs}</aside>
</div>
);
};
export default connectField(ImageField);
import SimpleSchema from 'simpl-schema';
import 'uniforms-bridge-simple-schema-2';
import ImageField from '../../ui/components/ImageField';
const BrandsSchema = new SimpleSchema({
//...
logo: {
type: Object,
uniforms: ImageField,
},
'logo.url': String,
'logo.public_id': String,
//...
});
export default BrandsSchema;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.