notacoder
notacoder

Reputation: 33

Upload and display image file through via input tag in react-redux

I have an input tag inside a component that uploads a singe image.

<input 
      type="file"
      accept=".png,.jpeg"
      onChange={e => dispatch(setProfileImage(e.target.files[0]))}
/>

From what I can see, the image gets saved in the state after I dispatch an action and save it to the state through a reducer.

My problem is this: In another component, I access the image in the state via useSelector and use it as the source in an image tag, but the image appears broken. Basically, I just want to be able to use the image saved in the state as the source of an image tag.

Any explanation, tutorial, or link be greatly appreciated. I'm trying to avoid using backend as the application I am working on is very small and there is no need for one but am willing to if that's the easiest answer.

Thank you!

Upvotes: 1

Views: 1288

Answers (1)

Samira
Samira

Reputation: 2733

create a url for image the put it in src of img tag :

   const ImageUrl =  URL.createObjectURL(file);

or

<img src={URL.createObjectURL(file)}  alt={file.name} />

Upvotes: 2

Related Questions