Skip to content
The Chat Archive
gpt-4o-2024-05-13· OpenAI WildChat-4.8M (AI2)

import { ChangeEvent, CSSProperties, useState } from "react" import styles from…

  1. User

    import { ChangeEvent, CSSProperties, useState } from "react" import styles from "./upload-card.module.css" import { Icon } from "../icon/icon.component.tsx" import classNames from "classnames" import { Config } from "../../utils/config.ts"

    // type buildFormDataValueFromFilePath = { // path: string; // name: string; // mimeType: string; // };

    export function UploadCard({ photo, className, style, wrapperStyle, }: { photo: string | null className?: string style?: CSSProperties wrapperStyle?: CSSProperties }) { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------

    const [selectedImage, setSelectedImage] = useState<string | null>(null)

    // --------------------------------------------------------------------------- // functions // ---------------------------------------------------------------------------

    async function handleImageChange(event: ChangeEvent) { const files = event.target.files if (!files || files.length === 0) return

    const file = files[0]
    const form = new FormData()
    form.append("file", file)
    
    try {
      const response = await fetch(`${Config.url}/api/file/upload`, {
        method: "POST",
        body: form,
      })
    
      if (!response.ok) {
        console.error("Error uploading file")
        return
      }
    
      const data = await response.json()
      console.log("===================filename=================")
      console.log(data)
      console.log("==================end filename==================")
      // Assuming the response contains an array under “filenames” key
      const filename = data.filenames && data.filenames[0]
      // const fullPath = `${Config.url}/uploads/${filename}`
      setSelectedImage(filename)
    } catch (error) {
      console.error("Error uploading file", error)
    }
    

    }

    // async function handleImageChange(event: ChangeEvent) { // if (event.target.files && event.target.files[0]) { // const reader = new FileReader() // reader.onload = (e) => { // if (e.target?.result) { // setSelectedImage(e.target.result as string) // } // } // reader.readAsDataURL(event.target.files[0]) // } // } console.log("=================selectedImage===================") console.log(selectedImage) console.log("=================end selectedImage===================") // --------------------------------------------------------------------------- return ( <div style={wrapperStyle} className={classNames(styles.container, className)} > <img style={style} // src={selectedImage || photo || ""} src={Config.imageUrl + selectedImage || photo || ""} className={styles.profileImg} alt="img" /> <Icon name={"fa-solid fa-up-from-line"} size="1.6" className={styles.icon} /> Upload photo <input type="file" id="files" style={{ visibility: "hidden" }} onChange={handleImageChange} /> ) } I want to send selectedImage as props

  2. Assistant

    To send the selectedImage as props to another component, you need to lift the state up to a common parent component that can then pass selectedImage down as props to its children. Here's how you can do it:

    1. Create a parent component that handles the state:

      import { useState } from "react";
      import { UploadCard } from "./UploadCard";
      import { AnotherComponent } from "./AnotherComponent"; // Replace with actual import
      
      export function ParentComponent() {
        const [selectedImage, setSelectedImage] = useState<string | null>(null);
      
        return (
          <div>
            <UploadCard
              photo={null}
              setSelectedImage={setSelectedImage}
            />
            <AnotherComponent selectedImage={selectedImage} />
          </div>
        );
      }
      
    2. Update the UploadCard component to accept setSelectedImage as a prop:

      import { ChangeEvent, CSSProperties } from "react";
      import styles from "./upload-card.module.css";
      import { Icon } from "../icon/icon.component.tsx";
      import classNames from "classnames";
      import { Config } from "../../utils/config.ts";
      
      export function UploadCard({
        photo,
        className,
        style,
        wrapperStyle,
        setSelectedImage,
      }: {
        photo: string | null;
        className?: string;
        style?: CSSProperties;
        wrapperStyle?: CSSProperties;
        setSelectedImage: (image: string | null) => void;
      }) {
        // ---------------------------------------------------------------------------
        // functions
        // ---------------------------------------------------------------------------
      
        async function handleImageChange(event: ChangeEvent<HTMLInputElement>) {
          const files = event.target.files;
          if (!files || files.length === 0) return;
      
          const file = files[0];
          const form = new FormData();
          form.append("file", file);
      
          try {
            const response = await fetch(`${Config.url}/api/file/upload`, {
              method: "POST",
              body: form,
            });
      
            if (!response.ok) {
              console.error("Error uploading file");
              return;
            }
      
            const data = await response.json();
            console.log("===================filename=================");
            console.log(data);
            console.log("==================end filename==================");
            // Assuming the response contains an array under “filenames” key
            const filename = data.filenames && data.filenames[0];
            // const fullPath = `${Config.url}/uploads/${filename}`
            setSelectedImage(filename);
          } catch (error) {
            console.error("Error uploading file", error);
          }
        }
      
        console.log("=================selectedImage===================");
        console.log(selectedImage);
        console.log("=================end selectedImage===================");
        // ---------------------------------------------------------------------------
        return (
          <div
            style={wrapperStyle}
            className={classNames(styles.container, className)}
          >
            <img
              style={style}
              src={Config.imageUrl + selectedImage || photo || ""}
              className={styles.profileImg}
              alt="img"
            />
            <label htmlFor="files" className={styles.iconBlock}>
              <Icon
                name={"fa-solid fa-up-from-line"}
                size="1.6"
                className={styles.icon}
              />
              <p>Upload photo</p>
            </label>
            <input
              type="file"
              id="files"
              style={{ visibility: "hidden" }}
              onChange={handleImageChange}
            />
          </div>
        );
      }
      
    3. Create the child component (AnotherComponent) that receives selectedImage as a prop:

      import { CSSProperties } from "react";
      
      export function AnotherComponent({
        selectedImage,
      }: {
        selectedImage: string | null;
      }) {
        return (
          <div>
            {selectedImage ? (
              <img src={selectedImage} alt="Uploaded" />
            ) : (
              <p>No image uploaded yet.</p>
            )}
          </div>
        );
      }
      

    This will ensure that the selectedImage state is managed in the parent component and both UploadCard and AnotherComponent can use it accordingly.