Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

htmlFor for input files label display

I was trying to set custom display for input type=file , but htmlFor with selecting id is not working .

By default input type=file displays as

Choose file(as button) - no file selected

I am trying to change those names "Choose files" and "no file selected" to my custom display , how can i achieve this ? I trying htmlFor with selecting id of the input field , but did not work out . I tried using label attribute but the text is being places on top of "Choose file" button.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s my tryout so far :

 <label className="form-label" htmlFor='input-file'> select.....</label>
                        <input
                             className="form-control form-control-lg form-control-solid"
                             type="file"
                             id="input-file"
                             name="thumbnailImg"
                             value={undefined}
                             onChange={(e) => file_choosen(e)}
                           />

The output is like :

select...
[Choose File] [no file selected]

I am trying to display something like :

[select...] [***custom no file selected here***]

>Solution :

If you do not wish to use the default input element then you need to:

  1. Hide the input element
  2. Use a button that you can style to your wishes
  3. On click then trigger the input file click
import { useRef, useState } from "react";

export default function App() {
  const ref = useRef();
  const [file, setFile] = useState(null);

  function file_chosen() {
    setFile(ref.current.files[0]);
  }
  return (
    <div>
      <div style={{ display: "flex", flexDirection: "row", gap: 4 }}>
        <button onClick={() => ref.current.click()}>Select file</button>
        <p>{file === null ? "No file chosen" : "1 file selected"}</p>
      </div>
      <input
        onChange={file_chosen}
        ref={ref}
        type="file"
        style={{ display: "none" }}
      />
    </div>
  );
}

codesandbox example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading