I want to create a button on my site that will allow the user to upload a file from their device (computer, phone).
I have already made this button and it opens a window where you can select a file.
But I ran into a problem: I would like to display the name of this file on the page.
I have this component highlighted in orange:
export default function BoxForChoiceFile() { return ( <Card sx={styles.CommonStyle}> <SelectFileButton></SelectFileButton> </Card> ); }
And in the BoxForChoiceFile component there is a button for choosing a file
export default function SelectFileButton() { const fileInput = useRef(); const selectFile = () => { fileInput.current.click(); } return ( <div> <input type="file" style={{ "display": "none" }} ref={fileInput} /> <Button onClick={selectFile} className='btn btn-primary' sx={styles.DispositionBottom}> <span>Upload</span> </Button> </div> ) }
Advertisement
Answer
In addition to what Alberto Anderick Jr answered, this is how you can pass the file name from the child component to the father component and show it below SelectFileComponent, in your BoxForChoiceFile :
export default function BoxForChoiceFile() { const [fileName, setFileName] = useState(""); return ( <div> <Card sx={styles.CommonStyle}> <SelectFileButton setFileName={setFileName} /> </Card> <h5>{fileName}</h5> </div> ); }
and in your SelectFileComponent:
export default function SelectFileButton(props) { const {setFileName} = props; const [file, setFile] = useState(null); const fileInput = useRef(); const selectFile = () => { fileInput.current.click(); }; const updateName = () => { setFile(fileInput.current.files[0]); setFileName(fileInput.current.files[0]?.name); } return ( <div> <input type="file" style={{ display: "none" }} ref={fileInput} onChange={updateName} /> <button onClick={selectFile} className="btn btn-primary"> <span>Upload</span> </button> </div> ); }