1

hi i need help migrating this class component to the default export function as my code is in the default export function and i need help to pass it to that format as i cant

import React, { Component } from "react";

export default class SingleImageUploadComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      file: null
    };
    this.uploadSingleFile = this.uploadSingleFile.bind(this);
    this.upload = this.upload.bind(this);
  }

  uploadSingleFile(e) {
    this.setState({
      file: URL.createObjectURL(e.target.files[0])
    });
  }

  upload(e) {
    e.preventDefault();
    console.log(this.state.file);
  }

  render() {
    let imgPreview;
    if (this.state.file) {
      imgPreview = <img src={this.state.file} alt="" />;
    }
    return (
      <form>
        <div className="form-group preview">{imgPreview}</div>

        <div className="form-group">
          <input
            type="file"
            className="form-control"
            onChange={this.uploadSingleFile}
          />
        </div>
        <button
          type="button"
          className="btn btn-primary btn-block"
          onClick={this.upload}
        >
          Upload
        </button>
      </form>
    );
  }
}

https://codesandbox.io/s/pedantic-brattain-irypt?file=/src/App.js

1 Answer 1

3
import React, { useState } from "react";

const SingleImageUploadComponent = () => {
  const [file, setFile] = useState(null);

  function uploadSingleFile(e) {
    setFile(URL.createObjectURL(e.target.files[0]));
    console.log("file", file);
  }

  function upload(e) {
    e.preventDefault();
    console.log(file);
  }

  return (
    <form>
      <div className="form-group preview">
        {file && <img src={file} alt="" />}
      </div>

      <div className="form-group">
        <input
          type="file"
          className="form-control"
          onChange={uploadSingleFile}
        />
      </div>
      <button
        type="button"
        className="btn btn-primary btn-block"
        onClick={upload}
      >
        Upload
      </button>
    </form>
  );
};

export default SingleImageUploadComponent;

CodeSandbox Link

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, just one more query, the image is not displayed when uploading it
but as you can see, the image data is being fetched and is being displayed in the console.
Daniel, I forgot to parse the image URL in the previous example, that's why the Image was not being previewed. I hope you already figured it out, if not then do check out the updated code :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.