Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default text in input type=“file” in reactjs?

Tags:

reactjs

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.

like image 727
leafend617 Avatar asked Apr 27 '20 21:04

leafend617


People also ask

How do I change the value of an input type file?

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.

How do you handle file input in React?

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.

How do you change type in React?

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.


1 Answers

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!

like image 131
Dacre Denny Avatar answered Oct 29 '22 19:10

Dacre Denny