Personalize the HTML <input> tag using the attribute type="file"

Within the React site, there is a field where users can select a file from their computer and view the file path.

To achieve this functionality, I used an HTML input with type="file"...

         <div className="inline-flex w-full justify-between">
          <input
            id="fileInput"
            onChange={chooceFile}
            type="file"
            className={clsxm(
              'w-full text-sm',
              'text-[#FFFFFF] file:float-right file:mr-0 file:text-[#FFFFFF]',
              'file:bg-[grey]',
              'file:px-3 file:text-xs',
              'file:font-medium '
            )}
          />
        </div>

...and I need assistance in customizing this field. Specifically, I have two questions:

  1. How can I change the default button label from "Choose File" to "Any text"?
  2. How do I alter the default label displayed when no file is selected from "No file chosen" to "Please choose a file"?

Answer №1

Learn how to implement this feature in React with tailwind styling


import { useState } from "react";

export default function Home() {
  const [file, setFile] = useState("");

  const handleFile = (e) => {
    setFile(e.target.files[0].name);
  };

  return (
    <div className="w-6/12 mx-auto bg-gray-800 text-white rounded-sm">
      <div className="flex items-center justify-between p-2">
        <h3 className="text-white">{file ? file : "Select a file"}</h3>
        <label htmlFor="file" className="cursor-pointer">
          <div className="bg-gray-400 gap-1.6 px-2 flex  items-center font-normal border-2 border-black">
            <span>Click here</span>
          </div>
          <input
            id="file"
            type="file"
            className="hidden"
            onChange={handleFile}
          />
        </label>
      </div>
    </div>
  );
}



Answer №2

If you want to seamlessly integrate input functionality into your visualization, consider overlaying the input element on top of the visual representation. The input is solely responsible for selecting a file and providing feedback, making it easy to replicate this behavior using just HTML, CSS, and a touch of JavaScript:

document.querySelectorAll('.file-input').forEach(fileInputWrapper => {

  const text = fileInputWrapper.querySelector('span');
  const input = fileInputWrapper.querySelector('input');

  input.addEventListener('change', event => {

    if (input.files.length === 1) text.textContent = input.files[0].name;
    else if (input.files.length > 1) text.textContent = `${input.files.length} files selected`;
    else input.textContent = 'Please select a file';

  })

})
.file-input {
  display: flex;
  position: relative;
  align-items: center;
}
.file-input input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}
.file-input span {
  padding: 10px;
}
<div class="file-input">
  <input multiple type="file" />
  <span>Please select a file</span>
  <button>Any Text</button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve JSON data generated within a JavaScript-powered webpage

My issue involves two HTML pages: 1) The first HTML Page (page1.html): <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script> <script type="text/ ...

Tips for merging two arrays in NextJS?

I need help with a minor issue I'm facing. In my app, I am creating data tables and retrieving data from two different API endpoints. The first endpoint returns data like this (e.g. offers): { id: 1, product_id: 1, name: 'some name', et ...

Transform the inline style attributes found in the HTML code into CSS styling

After creating a webpage using Bootstrap Studio, I realized that all the style attributes are inline and I want to move them to a separate CSS file. However, I am facing difficulty in doing so as when I add an image using 'background-image:url('i ...

What is the best way to close a popup window?

Is there a way to close my popup? function hidePopup(){ document.getElementById("popup-1").classList.remove("active"); } @import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap'); .popup .overlay{ positio ...

Identify and forward to the mobile-friendly version of the site

I am currently working on a website that requires separate files for mobile view as the html layout poses challenges in making it responsive. My goal is to find code that can detect if the user is accessing the site from a mobile device, and automatically ...

Learn how to customize the background color of the DropdownToggle when a DropdownItem in Bootstrap 4 is clicked

Is it possible to modify the background color of DropdownToggle when selecting DropdownItem? Additionally, is there a way to adjust the top and bottom blue borders when clicking DropdownToggle? Picture 1: The image depicts the initial appearance before se ...

Steps for eliminating redundant lines in a CSS drop-down navigation bar

When looking at the following CSS code, I noticed that the bottom and top borders seem to overlap, creating a thick line. I'm having trouble figuring out how to remove it. Any suggestions or advice would be greatly appreciated. Thank you! HTML Code: ...

What steps can I take to use CSS to disable a webpage?

Is there a way to create a disabled web page using CSS where users cannot click on any content and only view the content below the screen? ...

Refine the table by selecting rows that contain a specific value in the href attribute of the <a> tag, and display the parent row when the child row

I've been working on filtering and searching the table below based on the href value. My code successfully filters the displayed columns in the table, but it fails to work when I search for a string within the href attribute. For instance, if I searc ...

Determine if a draggable item is currently positioned over another element

In my body, there are several divs located: <div id="one"></div> <div id="two"></div> <div id="three"></div> All of these divs are draggable using jqueryUI: var $divs = $('#one, #two, #three'); $divs.draggab ...

Unexpected issue with accessing the jQuery class descendant

I am currently developing a photo gallery and I am trying to add some CSS styling to the first photo that is visible within my #wrapper div. Below is the code snippet I have been working on: $('.inside:first-of-type>div:nth-of-type(1)').css(& ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

MUI: Autocomplete cannot accept the provided value as it is invalid. There are no matching options for the input `""`

https://i.stack.imgur.com/KoQxk.png Whenever I input a value in the autocomplete component, an unresolved warning pops up... Here's how my input setup looks: <Autocomplete id="cboAdresse" sx={{ width: 100 + " ...

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

Design a table without borders that is compatible for pasting into a Word document

I've been struggling to figure out the correct format for creating a border-less table that, when pasted in Word, will maintain its appearance as shown below: <strong>Foo</strong> <ol> <li value="0">This is zero.</li&g ...

Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to ac ...

Error in Material-UI v1: Invalid Element Type for Swipeable Drawer

While working on my project, I added a SwipeableDrawer, but encountered the following error: × Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot t ...

Setting a default value in the material ui DatePicker

take a look at this attached image <MuiPickersUtilsProvider utils={DateFnsUtils} required={required} error={!!(touched && error)} > <DatePicker leftArrowIcon={<KeyboardArrowLeft/>} rightA ...

The animation of a disappearing div with CSS is not stopping when hovering over it

Hello, I've been working on a snackbar feature that appears and disappears on a set timer but also needs to pause when hovered over. Unfortunately, the current setup with setTimeout and useState is causing issues with this functionality. I have looke ...

Determine with jQuery whether the img src attribute is null

My HTML structure is as follows: <div class="previewWrapper" id="thumbPreview3"> <div class="previewContainer"> <img src="" class="photoPreview" data-width="" data-height=""><span>3</span> </div> </div> ...