Home > database >  htmlFor for input files label display
htmlFor for input files label display

Time:01-23

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.

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***]

CodePudding user response:

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

  • Related