Home > other >  React onClick issue while using CSS Active Pseudo Class
React onClick issue while using CSS Active Pseudo Class

Time:01-05

I have a React js code with below code functionalities. Input component has a "x" font awesome icon used to clear the data inside input field. The onClick functionality is not working on icon inside input form. But CSS active class is working fine. Code as given below

SandBox Link available at: sandbox-test-code

Input component as

const Input = () => {

function xClick(){
console.log("Hello");
}

return (    
<div className="inp_form">
  <input 
    className="inp"
    type="text"
    placeholder=" "
    autoComplete="nope"        
  />
  <i className="fas fa-times" onClick={xClick}></i>
  <label className="inp_lbl">First Name</label>
</div> );
}

At the same time, my CSS stylesheet contains below code

@import url('https://pro.fontawesome.com/releases/v5.10.0/css/all.css');
.inp_form{
position: relative;
margin: 1rem 2.5rem;
width: 30rem;    
height: 4.5rem;          
}
.inp{
position: absolute;
padding-right: 3rem;
width:100%;
height:100%;
top:0;
left:0;    
}
.inp_form > i{
position: absolute; 
top:25%;
font-size: 2rem;   
right:3%;
padding: 0.2rem 0.4rem;
transition: transform ease-in-out 50ms;
}
.inp_form > i:hover{  
color:red;   
}
.inp_form > i:active{
transform: scale(0.98%);
}

While pressing the button, console is not working. CSS active Pseudo is over writing button onClick function. Can anyone please help me get an answer for the same? Thanks in advance!

CodePudding user response:

The click event is a combo of mousedown and mouseup on the same element.
Since you scale the element out of existence (out of the mouse pointer more precise) you do not get the mouseup triggered on that element and so the click is never happening.

You could use onMouseDown event (demo)

<i className="fas fa-times" onm ouseDown={xClick}></i>

or you could use a wrapper element (demo)

<span className="icon" onClick={xClick}>
  <i className="fas fa-times"></i>
</span>

and

.inp_form > .icon {
  position: absolute;
  top: 25%;
  font-size: 2rem;
  right: 3%;
  padding: 0.2rem 0.4rem;
}
.inp_form > .icon i {
  transition: transform ease-in-out 50ms;
}
.inp_form > .icon:hover i {
  color: red;
}
.inp_form > .icon:active i {
  transform: scale(0.98%);
}
  •  Tags:  
  • Related