Hank
Hank

Reputation: 231

File Uplaod not working on Button click material-UI V1 ReactJs

File upload not working with Material-UI/Button click.

 <Button dense
      containerElement="label"
      label="label">
         <input
            style={{display: 'none'}}
            type="file" />
  </Button>

Upvotes: 2

Views: 4412

Answers (2)

Tim L
Tim L

Reputation: 935

Based on your self answer I'm guessing the problem is clicking the "Upload" button wasn't doing anything. Try using component="span" on the button instead.

<Button color="primary" variant="raised" component="span">Upload</Button>

Upvotes: 4

Hank
Hank

Reputation: 231

I have found the solution, but still needs a better way to implement it.

  import React, { Component } from 'react';
  import Button from 'material-ui/Button';
  import FormControl from '../formcontrol';

 class FileUpload extends Component {

constructor(props) {
    super(props);
    this.state = {
        file: []
    };
    this.onClick = this.onClick.bind(this);
    this.onChange = this.onChange.bind(this);
}

onClick = (inputValue) => {
    document.getElementById("fileInput").click()
}

onChange = (file, onChange) => {
    console.log(this.state.file);
}

render() {
    const { classes, onChange } = this.props;
    const { file } = this.state;

    return (
        <FormControl>
            <div>
                <input type="file" style={{ display: 'none' }} id="fileInput" onChange={e => {
                    this.onChange(e.currentTarget.files[0], onChange);
                }} />

                <Button className={classes.button}
                    raised
                    containerElement='label'
                    color="default"
                    label='My Label'
                    onClick={(event) => this.onClick(event)} }>
                    Upload
                < Icon className={this.props.classes.rightIcon}>file_upload</Icon>
                </Button>
            </div>
        </FormControl >
    );

  }

}

export default FileUpload;

Upvotes: 4

Related Questions