Home > Software engineering >  Close parent component
Close parent component

Time:08-16

I have a code with which the user can select a file from their device. The Card component will display its name and operations that can be done with the file.

But my problem is that I don't know how to close this component if the user wants to cancel the action.

    export default function DisplaySelectedFile() {
    const [fileName, setFileName] = useState("");
    console.log(setFileName)
    return (
        <div>
            <SelectFileButton setFileName={setFileName} />

            {fileName && <Card sx={styles.CommonStyle}>
                    <Stack spacing={10} direction="row" style={{paddingTop: "20px", paddingLeft: "10px"}}>
                        <div>{fileName}</div>

                        <Stack spacing={3} direction="row">
                            <div>Convert to</div>
                            <ConvertToFormatFile></ConvertToFormatFile>
                        </Stack>

                        <Button>CONVERT</Button>
                        <CloseIcon/>
                       
                        
                    </Stack>
                </Card>}
            
        </div>
    );
}

I have added a button which should close the entire Card component. If I add the following code

<CloseIcon onClick={() => setFileName(false)}/>

If I add the following code, then the component closes. But the next time you select a file, this component does not open (only after reloading the page).

Tell me how to close the Card component correctly so that you can open it without problems

CodePudding user response:

I would suggest to handle separately the card visibility and the file name value. Something like this should work:

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

const DisplaySelectedFile = () => {
  const [fileName, setFileName] = useState(null);
  const [showCard, setShowCard] = useState(false);

  const handleSelectFile = useCallback(
    (file) => {
      setFileName(file);
      file && setShowCard(true);
    },
    [setFileName, setShowCard]
  );

  const handleCloseCard = useCallback(() => {
    setShowCard(false);
    setFileName(null); // add this line only if it fits your use case
  }, [setFileName, setShowCard]);

  return (
    <div>
      <SelectFileButton setFileName={handleSelectFile} />

      {showCard && (
        <Card sx={styles.CommonStyle}>
          <Stack
            spacing={10}
            direction="row"
            style={{ paddingTop: "20px", paddingLeft: "10px" }}
          >
            <div>{fileName}</div>

            <Stack spacing={3} direction="row">
              <div>Convert to</div>
              <ConvertToFormatFile></ConvertToFormatFile>
            </Stack>

            <Button>CONVERT</Button>
            <CloseIcon onClick={handleCloseCard} />
          </Stack>
        </Card>
      ) || null}
    </div>
  );
}

export default DisplaySelectedFile;
  • Related