I have a functional component that will sometimes return a form for file selection, and sometimes it will return something else.
If I select my file, the name of the file will show up next to the "select file" button, however if I render something else, and then return to rendering the file input, the name of the file is lost, and the text goes back to "Select file..."
I'm keeping the file in state as shown below, but I'm unable to put the filename back on the input, so that the user can see that a file has been selected.
I've tried an approach using Ref as you can see below, but it's not working.
What can I do?
import { useState, useRef } from 'react'
import { Form } from 'react-bootstrap'
const MyComponent = () => {
const [file, setFile] = useState(undefined)
const fileRef = useRef(null)
fileRef.current = file
const onChange = event => {
setFile(event.target.files[0])
}
if(something) {
return (<div></div>)
} else {
return (<div>
<Form.Group controlId="myFileInput" className="mb-3">
<Form.Label>Select file</Form.Label>
<Form.Control type="file" onChange={onChange} ref={fileRef}/>
</Form.Group>
</div>
}
}
You can fix it by using CSS display none instead remove this element
<div style={{display: something ? "block" : "none"}}></div>
<div style={{ display: !something ? "block" : "none" }}>
<Form.Group controlId="myFileInput" className="mb-3">
<Form.Label>Select file</Form.Label>
<Form.Control type="file" onChange={onChange} ref={fileRef} />
</Form.Group>
</div>