I know this probably seems trivial, but I am a newbie and I am obviously missing something.
I am trying to create an array of what appear to be JSON objects to pass to react-image-gallery. See here NPM react-image-gallery
According to that web page, I need to do something like:
const images = [
{
original: 'https://picsum.photos/id/1018/1000/600/',
thumbnail: 'https://picsum.photos/id/1018/250/150/',
},
{
original: 'https://picsum.photos/id/1015/1000/600/',
thumbnail: 'https://picsum.photos/id/1015/250/150/',
},
{
original: 'https://picsum.photos/id/1019/1000/600/',
thumbnail: 'https://picsum.photos/id/1019/250/150/',
},
];
class MyGallery extends React.Component {
render() {
return <ImageGallery items={images} />;
}
}
However, note, I am not using the thumbnail, so I only need original.
Here is my code:
import React, { Fragment, useState } from 'react';
import axios from 'axios';
import ImageGallery from 'react-image-gallery';
//import '../image-gallery.css'
import "react-image-gallery/styles/css/image-gallery.css";
const AddNewItem = () => {
var [fileState, setFile] = useState([]);
var fileObj = {};
//bunch of irrelevant code
//Image Preview
const onChange = e => {
//setFile(e.target.files[0]);
fileObj = e.target.files[0];
console.log("AddNewItem fileObj: ", fileObj)
setFile(fileState => [...fileState, JSON.parse(`"orignal: ${URL.createObjectURL(fileObj)}"`)]);
}
//bunch of irrelevant code
return (
< Fragment >
{console.log("AddNewItem onChange fileState: ", fileState)}
<form id="myForm" onSubmit={onSubmit}>
<div className="container">
<div className="row ">
<div className="col">
<label className="mt-3 mb-0">Image:</label><br />
<input type="file" id="image" name="image" onChange={onChange}></input><br />
<button type="submit" className="mt-3">Submit</button>
</div>
<div className="col">
{fileState.length > 0 ? <ImageGallery items={fileState} showThumbnails={false} /> : ""}
</div>
</div>
</div>
</form>
</Fragment >
);
When I upload my first image, fileState is equal to the following, and I get the Failed prop type error:
When I upload a second image, fileState looks like:
And when there are 2 images in fileState, I do not get the error.
And no images are displayed by the gallery. I do get the arrow and play / pause button, but I do not see any images. But I am not entirely sure I have imported the image-gallery.css correctly according to the npm webpage mentioned above. But if that is an issue, then I will post another question on here.
Am I doing something wrong in the way that I am constructing fileState? If so, what can I do to fix it? Thanks.
You should pass an object to JSON.parse
:
JSON.parse(`{"original": "${URL.createObjectURL(fileObj)}"}`)
Also, you have a typo, the key should be original
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments