Upload File using ReactJS via BlueImp FileUpload jQuery plugin

5122014009 picture 5122014009 · Jan 20, 2014 · Viewed 15.6k times · Source

This is a newbie to ReactJS.

Could anyone please advise on what to use or how to have a form (with a few input boxes and a file selector) be uploaded in React?

Have been wrecking my nerves trying to use BlueImp JQuery-file-upload plugin. The error messages are cryptic and have been unsuccessful getting any useful help from google.

My code is as follows:

<form id="myForm" enctype="multipart/form-data" onSubmit={this.handleSubmit}>
  <input type="text" name="name">
  <input type="text" name="lastName">
  <input type="file" accept="image/*" name="myPic">
</form>

// Inside handleSubmit() of my component
$('#myForm").fileupload('add', {url: "myurl"});

Thanks!

Answer

Ross Allen picture Ross Allen · Mar 5, 2014

Using a jQuery plugin inside React is reasonable, but because React keeps its own virtual representation of the DOM you should avoid using jQuery selectors.

Use the event target to get a reference to the real DOM node when your form is submitted, and wrap it in a jQuery object to access the plugin:

React.createClass({
  handleSubmit: function(event) {
    $(event.target).fileupload('add', {url: "myurl"});
  },
  render: function() {
    return (
      <form enctype="multipart/form-data" onSubmit={this.handleSubmit}>
        <input type="text" name="name" />
        <input type="text" name="lastName" />
        <input type="file" accept="image/*" name="myPic" />
      </form>
    );
  }
});