I have a Floating button (material ui) in my react project. I want to open "choose file" dialoge box whenever I click it. I am not getting any solution to do that. I tried doing this but didn't work. and I don't want to use jquery.
</div>
<input id="myInput" type="file" style="visibility:hidden" />
<FloatingActionButton className="floatingButton" backgroundColor='#293C8E' onClick ="$('#myInput').click();">
<ContentAdd />
</FloatingActionButton>
</div>
Can someone please tell me what exactly I need to do?
Basic example (does not include what to do with selected file):
<div>
<input id="myInput" type="file" ref={(ref) => this.upload = ref} style={{ display: 'none' }} />
<FloatingActionButton
className="floatingButton"
backgroundColor='#293C8E'
onClick={(e) => this.upload.click() }
>
<ContentAdd />
</FloatingActionButton>
</div>
So, your FloatingActionButton's onClick handler manually fires the click() handler of a hidden file upload control (input type="file"). A reference to the hidden upload control is obtained by putting a ref callback on it and storing that reference in "this.upload" (could also use DOM or jQuery to do that, but ref is preferred in React)
here is a working jsFiddle: https://jsfiddle.net/432yz8qg/58/
You can do the trick with the help of <label/>
tag:
<label htmlFor='myInput'>
<input id="myInput" type="file" style={{visibility: 'hidden'}} />
<FloatingActionButton
className="floatingButton"
backgroundColor='#293C8E'
>
<ContentAdd />
</FloatingActionButton>
</label>
I solved this problem in a more React way than Jeff solution though my solution imply the use of multiple CSS rules.
I used a FlatButton with the props containerElement set to "label" :
const { FlatButton, SvgIcon, MuiThemeProvider, getMuiTheme } = MaterialUI;
class Example extends React.Component {
render() {
const buttonStyle = {
minWidth: '56px',
width: '56px',
minHeight: '56px',
height: '56px',
borderRadius: '28px',
};
return (
<div>
<FlatButton
containerElement="label"
backgroundColor='#293C8E'
style={buttonStyle}
>
<input type="file" style={{ display: 'none' }} />
</FlatButton>
</div>
);
}
}
const App = () => (
<MuiThemeProvider muiTheme={getMuiTheme() }>
<Example />
</MuiThemeProvider>
);
ReactDOM.render(
<App />,
document.getElementById('container')
);
<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://rawgit.com/nathanmarks/3f5196f5973e3ff7807f2bab4e603a37/raw/f409f3bf5902c211b358a3ebe7b6cd366da551e8/mui-umd.js"></script>
<div id="container"></div>
More details here : https://stackoverflow.com/a/36262984/2590861
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With