File Upload In React

March 01, 2017

It turns out that uploading file with react is pretty easy and not different from the way it’s done in plain JavaScript. Let’s do it now

class FileUploader extends React.Component {
  state = { file: null }
  handleFileChange = (e) => {
  handleUpload = (e) => {
    const { file } = this.state;
    if(file) {
      const formData = new FormData();
      formData.append('file', this.state.file);
      //$.post("/path/to/server", formData);
    } else {
      //handle no file selected
        <input type="file" onChange={this.handleFileChange}/>
        <input type="submit" onClick={this.handleUpload} 
               value="Upload File" />

You can now check the params on the server endpoint when an actual request is made to decide how you want the file to be handled. If you’re wondering where the FormData class came from, please see the docs on MDN

That is all. Feel free to configure it to your business needs. Thank you for reading.

Damian Simon Peter

Hi, I am Damian Simon Peter a software developer based in Waterloo, Ontario. I have spent the past years working for early-stage startups, building backend and frontend applications primarily using Ruby and JavaScript. I own a System76 Galago Pro running Pop!_OS and absolutely love it.