Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda