-2

I am a beginner in React and only know how to use functions in React, but a lot of codes around are using class. How can I convert this to a function?

Also can someone explain why they use classes? I hate the syntax.

import React from 'react';

class ImageUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {file: '',imagePreviewUrl: ''};
  }

  _handleSubmit(e) {
    e.preventDefault();
    // TODO: do something with -> this.state.file
    console.log('handle uploading-', this.state.file);
  }

  _handleImageChange(e) {
    e.preventDefault();

    let reader = new FileReader();
    let file = e.target.files[0];

    reader.onloadend = () => {
      this.setState({
        file: file,
        imagePreviewUrl: reader.result
      });
    }

    reader.readAsDataURL(file)
  }

  render() {
    let {imagePreviewUrl} = this.state;
    let $imagePreview = null;
    if (imagePreviewUrl) {
      $imagePreview = (<img src={imagePreviewUrl} alt="Artwork"/>);
    } else {
      $imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
    }

    return (
      <div className="previewComponent">
        <form onSubmit={(e)=>this._handleSubmit(e)}>
          <input className="fileInput"
            type="file"
            onChange={(e)=>this._handleImageChange(e)} />
          <button className="submitButton"
            type="submit"
            onClick={(e)=>this._handleSubmit(e)}>Upload Image</button>
        </form>
        <div className="imgPreview">
          {$imagePreview}
        </div>
      </div>
    )
  }
}

export default ImageUpload;
halfer
  • 19,824
  • 17
  • 99
  • 186
Alixsep
  • 382
  • 2
  • 3
  • 13
  • 1
    Readers here will generally encourage you to give things a go first, since that is the best way to learn, and Stack Overflow would be overrun with requests for free labour if "convert dis 4 me plz" was on-topic. For your next question, please research the problem thoroughly before asking, and then show your working. Readers will appreciate the effort! – halfer Apr 15 '20 at 09:59

1 Answers1

1

Your code is already written as a Class based component. Here is an implementation of your class based component as a functional component with hooks.

import React, { useState } from "react";

function ImageUpload() {
  const [file, setFile] = useState("");
  const [imagePreviewUrl, setimagePreviewUrl] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    // TODO: do something with -> this.state.file
    console.log("handle uploading-", file);
  };

  const handleImageChange = (e) => {
    e.preventDefault();
    let reader = new FileReader();
    let file = e.target.files[0];

    reader.onloadend = () => {
      setFile(file);
      setimagePreviewUrl(reader.result);
    };

    reader.readAsDataURL(file);
  };

  let $imagePreview = null;
  if (imagePreviewUrl) {
    $imagePreview = <img src={imagePreviewUrl} alt="Artwork" />;
  } else {
    $imagePreview = (
      <div className="previewText">Please select an Image for Preview</div>
    );
  }

  return (
    <div className="previewComponent">
      <form onSubmit={(e) => handleSubmit(e)}>
        <input
          className="fileInput"
          type="file"
          onChange={(e) => handleImageChange(e)}
        />
        <button
          className="submitButton"
          type="submit"
          onClick={(e) => handleSubmit(e)}
        >
          Upload Image
        </button>
      </form>
      <div className="imgPreview">{$imagePreview}</div>
    </div>
  );
}

export default ImageUpload;
Ajin Kabeer
  • 2,096
  • 2
  • 9
  • 18