demonintherough
demonintherough

Reputation: 304

Button in label for custom file selector field

I'm attempting to make a custom file selector button. So instead of having a <input type='file'/> I would like to have a clickable button which does the same thing.

                <input
                  style={{ display: 'none' }}
                  id="raised-button-file"
                  type="file"
                  onChange={this.onFileChange}
                />
                <label htmlFor="raised-button-file">
                  <Button className="shapefile-icon" component = `span`>
                    <PublishIcon/>
                  </Button>
                </label>

I don't understand that when i remove the component = 'span' this stops the button from functioning correctly. It is no longer clickable unless i click the label area around the button. I'm curious as to why this is working this way as well as how to fix this.

Upvotes: 2

Views: 300

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81026

Rather than putting a Button inside a label, just have the Button be the label using component="label".

As far as the "why" for the behavior, this is unrelated to Material-UI and behaves the same way using a plain <button> element. The button gets the "default" behavior of the click rather than the label. You can get a span to behave the same way if you call event.preventDefault().

import React from "react";
import ReactDOM from "react-dom";

import Button from "@material-ui/core/Button";
import PublishIcon from "@material-ui/icons/Publish";

function App() {
  return (
    <div className="App">
      <input
        style={{ display: "none" }}
        id="raised-button-file"
        type="file"
        onChange={() => {}}
      />
      <Button
        htmlFor="raised-button-file"
        className="shapefile-icon"
        component="label"
      >
        <PublishIcon />
      </Button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit file input button

Upvotes: 1

Related Questions