I want to change default text on button that is "Choose File" when we use input type="file"
I read through the Change default text in input type="file"?, but my case is in reactjs.
And I was told "React generally doesn't use document.getElementById to get things done. " So is there a better solution?
Thanks so much for all of your help.
You can't. The only way to set the value of a file input is by the user to select a file. This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
files[0]) } function handleSubmit(event) { event. preventDefault() const url = 'http://localhost:3000/uploadFile'; const formData = new FormData(); formData. append('file', file); formData. append('fileName', file.name); const config = { headers: { 'content-type': 'multipart/form-data', }, }; axios.
In React Js, I can use a state variable to change the input type of an input element. I just use a state variable to hold the input type like <input type={inputType} /> . When I assign a valid input type to the inputType state variable, the input element will change to that type.
I don't believe there's a reliable, cross-browser solution for that. You could however do something like this instead:
<label htmlFor="filePicker" style={{ background:"grey", padding:"5px 10px" }}>
My custom choose file label
</label>
<input id="filePicker" style={{visibility:"hidden"}} type={"file"}>
Here the file input
element is "paired" with a corresponding label
element via the id
and for
attributes (note the in react, for
is instead specified by htmlFor
).
This pairing causes user click interaction with the label
element to trigger that default click behavior on the input
element - which in this case, would cause the OS file selector dialog to open.
This technique gives you control over the label of the file picker, and also allows you to specify styling for the pseudo "label-button" as required.
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With