Filth Filth - 1 month ago 19
Javascript Question

React JS Image Uploader | Change Background Image

I'm trying create a background image updater / uploader component.

An image is set on default however, if the user would like to update the background image I would like to update the state and store the image.

Research so far suggests I need to use the

<input type="file" />
element to enable the upload dialog box.

Is there another way around not using the input element? If the user is to click on the
<button>
element to show the dialog box and then update the background image.

export default class ChangeBackground extends React.Component {
constructor() {
super();
this.state = {
backgroundImage: ''
}
}

handleBackgroundChange() {
let backgroundImage = backgroundImage
this.setState({
backgroundImage: backgroundImage
});
}

render() {
return (
<div className="change-bg-wrap">
<input type="file" accept="image/*" />
<button>
<i className="fa fa-picture-o" style={{fontSize: 20}}></i>
</button>
</div>
)
}
}

Answer

Hide the input element with display: "none", then do some javascript so that when the button is clicked on it will trigger the <input>.

   triggerInput = () => {
        document.querySelector("input[type='file']").click();
    }
   <input type="file" accept="image/*" />
    <button onClick={this.triggerInput}>
        <i className="fa fa-picture-o" style={{fontSize: 20}}></i>
    </button>

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

Cache the querySelector value in a var as well

Edit: I don't think you can trigger a react event click() which is why I used native js. Correct me if I am wrong.