Reputation: 1730
I have a form on ReactJS webapp and I am trying to include a hover effect on an <input />
element. Following a template, I got to the code below. While I got the hover effect, the <input />
element doesn't catch the click event and the file explorer doesn't open for me to select a file.
<div className='hoverphoto'>
<span className='hover'>Upload</span>
<img src={`${ServerRoutes.IMAGES_ROUTE}default.jpg`} alt="..." className='imgavatar' />
<input className='upload' type="file" onChange={this.fileChangedHandler} />
</div>
I also tried placing the <input />
inside the <span />
, but the text pushed the <input />
and the <img />
to the right.
How can I fix this?
EDIT: Including the CSS classes:
.hoverphoto{
display: inline-block;
position: relative;
margin-top: -50px;
box-shadow: 0 10px 30px -12px rgba(0, 0, 0, 0.42), 0 4px 25px 0px rgba(0, 0, 0, 0.12), 0 8px 10px -5px rgba(0, 0, 0, 0.12);
border-radius: 50%;
height: 130px;
width: 130px;
}
.hover{
height: 130px;
width: 130px;
text-align:center;
color:white;
opacity:0;
transition: opacity .2s linear;
background-color:rgba(0,0,0,.7);
position: absolute;
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
border-radius: 50%;
}
.hover:hover{
opacity:1;
}
.imgavatar{
width: 100%;
height: auto;
vertical-align: middle;
border: 0;
cursor: pointer;
position: absolute;
border-radius: 50%;
}
.upload{
position:relative;
height: 130px;
width: 130px;
overflow: hidden;
cursor: pointer;
opacity: 0;
}
Upvotes: 0
Views: 1203
Reputation: 1730
Got to work creating an onClick
handler on the parent <div>
. For this, I created a ref
on the <input>
element and used it to force a click. This is the result:
.jsx
handleUpload = () => {
this.inputElement.click();
}
render() {
[...]
<div className='hoverphoto' onClick={this.handleUpload}>
<input
className='upload'
type="file"
accept="image/*"
onChange={this.handleFileChanged}
ref={input => this.inputElement = input}
/>
<img src={`${ServerRoutes.IMAGES_ROUTE}${this.state.profileUri}`} alt="..." className='imgavatar' />
<div className='span-wrapper'>
<span>Upload</span>
</div>
</div>
[...]
}
.css
.hoverphoto{
display: inline-block;
position: relative;
margin-top: -50px;
box-shadow: 0 10px 30px -12px rgba(0, 0, 0, 0.42), 0 4px 25px 0px rgba(0, 0, 0, 0.12), 0 8px 10px -5px rgba(0, 0, 0, 0.12);
border-radius: 50%;
height: 130px;
width: 130px;
overflow: hidden;
}
.hoverphoto .span-wrapper {
position: absolute;
bottom:0;
left:0;
background:rgba(0,0,0,0.8);
color:#fff;
text-align:center;
width:100%;
padding:5px;
}
.imgavatar{
width: 100%;
height: 100%;
left: 0;
bottom: 0;
vertical-align: middle;
border: 0;
z-index: 500;
position: absolute;
border-radius: 50%;
}
.imgavatar:hover {
opacity: 0.5;
cursor: pointer;
}
.upload{
opacity:0;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index: 500;
}
Upvotes: 1