Following up on my previous post, I wanted to share how to upload images from your React frontend to your server. It only takes a couple of lines of code, but if everything isn’t lined up, you will be pulling your hair out.

This example was built with Ionic. The form is universal to React frameworks, but rendering the avatar is unique to Ionic

For simplicity’s sake, we are going to build a component that both renders your image and allows for you to upload a new one. Let’s call it Avatar.tsx

First, let’s render an image.

/components/Avatar.tsx

import React, { useState } from "react";
import { IonText, IonAvatar } from "@ionic/react";

interface AvatarProps {
  imageURL: string;
  userID: string;
}

const Avatar: React.FC<AvatarProps> = ({ imageURL, userID }) => {
  const [url, setURL] = useState<string>("https://images.ctfassets.net/0jkr5d02o14t/
  4Tsq7upvRUHBdW4HwzeNEy/7f140b351543035dae54015d634c0df4/placeholder.png?h=250");


  const placeholder = "https://images.ctfassets.net/0jkr5d02o14t/4Tsq7upvRUHBdW4HwzeNEy/7f
  140b351543035dae54015d634c0df4/placeholder.png?h=250";

  if (imageURL && url === placeholder) {
    setURL(imageURL);
  }

  return (
    <div>
      <IonAvatar className="avatar">
        <img src={`${url}`} alt="avatar" />
      </IonAvatar>
      <IonText>
            className="edit-pic"
            onClick={}
          >
            Change Profile Picture
          </h5>
      </IonText>
    </div>
  );
};

export default Avatar;

#react #ionic-framework #programming

React: Uploading Images
1.50 GEEK