Reputation: 33
I am using ReactJS and Google's Material components for the web using RMWC (https://github.com/jamesmfriedman/rmwc). I have a parent component which contains an icon and a text under it. This icon has Material Design Ripples effect on it, which means that when I hover it or click it, an animation is triggered.
I would now like to trigger that same effect when I hover or click on the text that is under.
Here is the component:
export class Subject extends Component {
constructor(props) {
super(props)
}
triggerRippleHover() {
console.log("hovered");
// HERE
}
renderSubjectIcon(Icon) {
return (
<Icon className="subject-icon" />
)
}
render() {
return (
<div className="subject-container">
<Ripple unbounded>
<div className="subject-icon-container">
{this.renderSubjectIcon(this.props.icon)}
</div>
</Ripple>
<span onMouseEnter={this.triggerRippleHover}>{this.props.name}</span>
</div>
)
}
Basically, I just want to "extend" the zone that triggers the behavior of the icon (if that makes any sense).
I have been searching extensively but haven't been able to find an appropriate answer.
Thanks a lot for your help.
Upvotes: 3
Views: 10597
Reputation: 33
Thanks a alot for your answers, they have been helpful, I have managed to simulate the onMouseDown and onMouseUp events thanks to Jordan Enev answer (By triggering the activate() API of the ripples effect https://github.com/material-components/material-components-web/tree/master/packages/mdc-ripple) but not the hover, because there isn't any API for that.
I now realize that I need to trigger the :hover pseudo class of the Material Component, which seems not doable with the method.
Upvotes: 0
Reputation: 18644
You can try the following approach:
1.Get the <Icon />
ref as follow (refs documented here):
<Icon className="subject-icon" ref={element => this.iconRef = element} />
2.Once you have the <Icon />
ref, then in your triggerRippleHover
callback, you can programatically trigger mouseover
event (or the corresponding one) to the this.iconRef
. Here's another SO answer, that describes better how to trigger the event. Here's an example code snippet, that will give you insight about my idea:
triggerRippleHover() {
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
const event = new MouseEvent('mouseover', {
view: window,
bubbles: true,
cancelable: true
})
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
this.iconRef.dispatchEvent(event)
}
Upvotes: 8
Reputation: 2517
Here is the MDN article on how to trigger events: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
One approach could be the following:
var mouseoverEvent = new Event('mouseover');
myTrigger.addEventListener("mouseover", function(){
myMouseOver.dispatchEvent(mouseoverEvent);
});
Here is the full fiddle... https://jsfiddle.net/sarawinter79/sc2fzeqm/
Upvotes: 0