Create an upload file like a champ using React

Ernesto Jara Olveda
4 min readAug 3, 2020

--

Youll find the code at the end.

Here I am again, this pandemic left me w/out a job so I have free time and of course a bunch of bills to pay…

In today’s adventure I’ll help you with and upload file/image button built on create-react-app.

NOTE: Styles go on you xD

$ create-react-app appname

Oki then, once all the lovely dependencies and stuff are downloaded, create a new file I called it ./src/upload.js

The code is at the bottom

Inside your file create a component I named mine ImageUpload.
We are going to do it only with images, but It’ll work for any file… maybe ;3

go to google.com and grab a defaults user profile pic like the one in facebook.

We add to properties into our state:

  • file: This is what we are going to send to backend
  • imagePreviewUrl: we convert the blob to display the image we choose.

Well to upload a file first we need and input of type file add it to the return method

As you might notice it Im mexican, there for my browser is in spanish.
To play around with this input lets create a ref.

With the ref know we can interact with the input via react and stuff.

So now that we have that let us do the handler.

For some excuses I mean for security purposes the path of the pic is been hidden so you dont see where the pic at so when the onChange event triggers it comes with a fake path.

event triggers and in the parameter we get from the window, there is an object call target, with it comes and array of files… maybe, thats why we first check if file is not undefined, if not we tell the reader to read the content as a dataURL. then the onloaded callback is call

once it loads it has a result property we set it to our image preview and the file to our file let’s see it… not just yet, we need a image preview thingy.

under our input lets put an img tag and set the value equals to the preview state

so add a pic to it, click on it and choose yow pic

It is done by that, but lets do lil more in heaw. open the app.css and hide the input

any where it can fit, it is just to not show the input xDDD this is why we created the ref

now the input is not displayed, then add a button at the bottom of your jsx.

as the input “does not” exists anymore we need to fake a click on the button, in our button xDDD we click a button with another button TROLL xDD

but then what if I choose a wrong pic just like I did, I need to be remove lets hndle that

first create and If component

we add the remove handler and. it sets the file to null and put default pic back.

we can call it a done

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response