Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Keep input file text on re-creation of component

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>
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!