I have a code where I output images dynamically. And in the state I have an array with objects {url: null, name: null}
.
When I load an image, I get the image name
fine, but not url
. And i can’t understand why. Here is the complete code:
const [UploadLogos, setUploadLogos] = useState([
{ url: null, name: null}
])
const setParam = (Param, newParam, i) => {
setUploadLogos([
...UploadLogos.slice(0, i),
{ ...UploadLogos[i], [Param]: newParam },
...UploadLogos.slice(i + 1),
])
}
{
UploadLogos.map((Logo, i) => (
<ImageUpload
key={i}
Image={Logo.url}
setImage={(prev) => setParam("url", prev, i)}
Name={Logo.name}
setName={(prev) => setParam("name", prev, i)}
/>
))
}
ImageUpload.jsx
import React, { useRef } from 'react';
export function ImageUpload({Image, setImage, Name, setName}) {
const ref = useRef();
return (
<>
<input
type="file" accept="image/png" style={{display: "none"}} ref={ref}
onChange={event => {
const ImageURL = URL.createObjectURL(event.target.files[0])
const ImageName = event.target.files[0]['name']
setImage(ImageURL)
setName(ImageName)
console.log(ImageURL) ===> blob:http://localhost......
console.log(Image) ===> null
console.log(ImageName) ===> simpleImage.png
console.log(Name) ===> simpleImage.png
}}
/>
<button onClick={() => ref.current?.click()}>Upload Image</button>
</>
)
}
In the console in the component I showed what I was getting. And Image
is always null
, although, I put it in setImage(ImageURL)
.
What is the error?