Home > front end >  What is the proper Typing for props.src? (Typescript)
What is the proper Typing for props.src? (Typescript)

Time:05-21

I have the following component working, but I would like to make it a bit more "Typescripty" by typing the props properly. As you can see, right now I have it set to "any". Here's my code:

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

type ImageSrc =  React.SetStateAction<null>

//The line in question here
const AsyncImage = (props: any) => {
  const [loadedSrc, setLoadedSrc] = useState<ImageSrc>(null);
  useEffect(() => {
      setLoadedSrc(null);
      if (props.src) {
          const handleLoad = () => {
              setLoadedSrc(props.src);
          };
          const image = new Image();
          image.addEventListener('load', handleLoad);
          image.src = props.src;
          return () => {
              image.removeEventListener('load', handleLoad);
          };
      }
  }, [props.src]);
  if (loadedSrc === props.src) {
      return (
          <img {...props} alt=""/>
      );
  }
  return null;
};

export default AsyncImage

CodePudding user response:

You expect string as image src prop. Even if it would be another type, with typescript it should look like this (just use correct type in TProps type):

import React, {useState, useEffect, FC} from "react";

type TProps = {
    src: string;
};

//The line in question here
const AsyncImage:FC<TProps> = (props) => {
    const [loadedSrc, setLoadedSrc] = useState<string>("");
    useEffect(() => {
        setLoadedSrc("");
        if (props.src) {
            const handleLoad = () => {
                setLoadedSrc(props.src);
            };
            const image = new Image();
            image.addEventListener('load', handleLoad);
            image.src = props.src;
            return () => {
                image.removeEventListener('load', handleLoad);
            };
        }
    }, [props.src]);
    if (loadedSrc === props.src) {
        return (
            <img {...props} alt=""/>
        );
    }
    return null;
};
export default AsyncImage;

Here React.FunctionComponent (or React.FC) is a component type, needed for passing props properly.

  • Related