React: user-uploaded pics?

Folks, I’m working on a blog in React, kind of a WordPress clone, I guess, and I want users to be able to upload pictures. Any basic ideas on how to do this?

I’m thinking the form to make a post should have an input form, maybe something like this?

<input type="file" name="myImage" accept="image/*" />

But then how would that be stored in React? I’m thinking the form submission should create an <Image src="{image} alt="image /> thing that will go in the <Post />.

Also, the picture will eventually be stored in the Firebase Real-Time database that the blog is hooked up to. If you want to look at what I have so far, it’s here:
deployment

code

Hey there,

great work so far!

I think some better questions are:

  • Why do I want to store it in React?
  • Does that make sense?

I’m thinking the form submission should take data, put it somewhere, and the presentation layer, e.g. a React component, should render an output from the data.

1 Like

Thanks, I think you’re right! I had been coding this in a pattern:

  1. store it in the component
  2. refactor it to store it in the App
  3. refactor it to store it in the database

trying to do it in steps so I had control every step. This worked fine for strings and numbers, but maybe it’s not viable in this case.

I managed to get it hooked directly up to Firebase storage and have got it more or less working locally.

1 Like

Hey, how did you do that cat thing?! :slight_smile:

By the way, pics have been added!

https://z-project-cactus-wren.netlify.app/

1 Like

Alright, that makes sense!

You should put an onChange function to your file input and then store it in the state.

// say we have [files,setFiles] state
setFiles(e.target.files[0]);

// That is if you want to preview the image to the user.
// [image,setImage] state
    setImage(window.URL.createObjectURL(e.target.files[0]));

You can then store that file state in firebase, they have a detailed documentation on this on their storage documentation.

1 Like

Thanks, I’ll read that more carefully and give it a try.