Tailwind CSS customised file input

A showcase on how to customise a file input using Tailwind CSS

by DevJamesHay

HTML

<script src="https://cdn.tailwindcss.com"></script>
<div id="app"></div>

React

const { useState } = React;

// A default file input just with the styles changed using Tailwind CSS
const CustomStylesExample = () => {

  return (
  	<form>
      <input
        type="file"
        class="block w-full text-sm text-slate-500
          file:mr-4 file:py-2 file:px-4 file:rounded-md
          file:border-0 file:text-sm file:font-semibold
          file:bg-pink-50 file:text-pink-700
          hover:file:bg-pink-100"
      />
    </form>
  )
}


// A custom file input using React
const CustomInputExample = () => {
  const [selectedFile, setSelectedFile] = useState("Please select a file");

  return (
    <form>
      <div class="flex flex-row items-center">
        <input
          type="file"
          id="custom-input"
          onChange={(e) => setSelectedFile(e.target.files[0].name)}
          hidden
        />
        <label
          for="custom-input"
          class="block text-sm text-slate-500 mr-4 py-2 px-4
            rounded-md border-0 text-sm font-semibold bg-pink-50
            text-pink-700 hover:bg-pink-100 cursor-pointer"
        >
          Choose file
        </label>
        <label class="text-sm text-slate-500">{selectedFile}</label>
      </div>
    </form>
  );
};


const container = document.getElementById('app');
const root = ReactDOM.createRoot(container);

root.render(
	<div class="p-8 space-y-8">
    <CustomStylesExample />
    <CustomInputExample />
  </div>
);