Is there any way to detect middle click in React JS? - javascript

I am trying to find a way to detect middle click event in React JS but so far haven't succeeded in doing so.
In Chrome React's Synthetic Click event does show the button clicked ->
mouseClickEvent.button === 0 // Left
mouseClickEvent.button === 1 // Middle but it does not execute the code at all
mouseClickEvent.button === 2 // Right (There is also onContextMenu with event.preventDefault() )
Please share your views.

If you are using a stateless component:
JS
const mouseDownHandler = ( event ) => {
if( event.button === 1 ) {
// do something on middle mouse button click
}
}
JSX
<div onMouseDown={mouseDownHandler}>Click me</div>
Hope this helps.

You can add a mouseDown event and then detect the middle button click like:
handleMouseDown = (event) => {
if(event.button === 1) {
// do something on middle mouse button click
}
}
You code might look like:
class App extends React.Component {
constructor() {
super();
this.onMouseDown = this.onMouseDown.bind(this);
}
componentDidMount() {
document.addEventListener('mousedown', this.onMouseDown);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.onMouseDown);
}
onMouseDown(event) {
if (event.button === 1) {
// do something on middle mouse button click
}
}
render() {
// ...
}
}
You can find more information on MouseEvent.button here:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
Be careful. Using mousedown won't always get you the behavior you want. A "click" is both a mousedown and a mouseup where the x and y values haven't changed. Ideally, your solution would store the x and y values on a mousedown and when mouseup occurs, you would measure to make sure they're in the same spot.
Even better than mousedown would be pointerdown. This configures compatibility with "touch" and "pen" events as well as "mouse" events. I highly recommend this method if pointer events are compatible with your app's compatible browsers.

The modern way of doing it is through the onAuxClick event:
import Card from 'react-bootstrap/Card';
import React, { Component } from 'react';
export class MyComponent extends Component {
onAuxClick(event) {
if (event.button === 1) {
// Middle mouse button has been clicked! Do what you will with it...
}
}
render() {
return (
<Card onAuxClick={this.onAuxClick.bind(this)}>
</Card>
);
}

You can use React Synthetic event as described below
<div tabIndex={1} onMouseDown={event => { console.log(event)}}>
Click me
</div>

You can keep onClick. In React, you have access to nativeEvent property from where you can read which button was pressed:
const clickHandler = (evt) => {
if (e.nativeEvent.button === 1) {
...
}
}
return (
<a onClick={clickHandler}>test</a>
)

Related

How can i transfer focus to the next focusable element inside an onFocus handler of another element?

I have a react app, and i am trying to build a focus trapper element, that lets the user tab through elements normally but won't let you focus outside their container.
What works
I am doing so by rendering a first and last "bounder" to sandwich the actual content between two focusable divs that should pass the focus forwards or backwards based on the direction they received it from.
the code for the container:
export class QKeyBinder
extends ComponentSync<QKeyBinder_Props, State> {
private firstTabBinder: React.RefObject<HTMLDivElement> = React.createRef();
private lastTabBinder: React.RefObject<HTMLDivElement> = React.createRef();
protected deriveStateFromProps(nextProps: QKeyBinder_Props): State {
return {};
}
private renderFirstTabBounder() {
return <div
tabIndex={0}
ref={this.firstTabBinder}
className={'q-key-binder__tab-binder'}
role={'tab-binder'}
onKeyDown={(e) => {
if (e.key === 'Tab' && e.shiftKey) {
e.preventDefault();
stopPropagation(e);
return this.lastTabBinder.current!.focus();
}
}}/>;
}
private renderLastTabBounder() {
return <div
tabIndex={0}
ref={this.lastTabBinder}
className={'q-key-binder__tab-binder'}
role={'tab-binder'}
onKeyDown={(e) => {
if (e.key === 'Tab' && !e.shiftKey) {
e.preventDefault();
stopPropagation(e);
return this.firstTabBinder.current!.focus();
}
}}/>;
}
render() {
const className = _className('q-key-binder', this.props.className);
return <div className={className}>
{this.renderFirstTabBounder()}
{this.props.children}
{this.renderLastTabBounder()}
</div>;
}
}
As you can see, i have it working by pressing tab again.
I want the bounders to have a onFocus handler to pass the focus along once they get it.
What didn't work
Since i can't know beforehand who the next focusable element is, I tried dispatching a keyboard event, e.g:
onFocus={(e}=>{
document.body.dispatchEvent(new KeyboardEvent('keypress',{key:'Tab'}))
}}
Dispatching the event on the body.document, the e.target, the body, the window, none of these work.
Just can't seem to simulate another tab press, or find a way to focus the next element without depending on a selector, or a wrapper, which causes extra complexity.
Any help would be much appreciated!

Can't call e.preventDefault on React element (div)

I'm building a fake text area that supports highlighting and cursor navigation. As part of this, I need to support keyboard shortcuts like Alt + left/right keys. In order to do this, I want to prevent the default browser actions from happening (in Firefox on Windows Alt + left/right navigates forward or back a page).
The issue is that the event object that is passed to my onKeyDownHandler function doesn't contain the preventDefault method. How can I get access to this method?
Here's a simplified version of my code:
import React from 'react';
class FakeTextArea extends React.Component {
constructor(props) {
super(props);
this.onKeyDownHandler = this.onKeyDownHandler.bind(this);
}
onKeyDownHandler(e) {
if (e.key === 'arrowleft' && e.altKey) {
// e.preventDefault() doesn't exist
console.log('no prevent default?');
}
}
render() {
return (
<div
tabIndex="0"
onKeyDown={this.onKeyDownHandler}
>
Here is some random text that I want to have in here
</div>
);
}
}
export default FakeTextArea;
[UPDATE] The event is just not visible, but it's there, you can find it with an old and great console.log(e.preventDefault)!
[OLD ANSWER] Use the event from nativeEvent:
onKeyDownHandler(e) {
if (e.key === 'arrowleft' && e.altKey) {
e.nativeEvent.preventDefault()
console.log('no prevent default?');
}
}
Reference: https://reactjs.org/docs/events.html#overview

Prevent page scrolling when mouse is over one particular div

My question is similiar to this How to prevent page scrolling when scrolling a DIV element? but I'm wondering if there is an approach with css and/or react that does not require jQuery.
I want to disable page scrolling on a mouseWheel event when the cursor is over one particular div.
The div is a graph which zooms on a mouseWheel event, and is rendered by a React component.
I've tried e.preventDefault however chrome tells me
Unable to preventDefault inside passive event listener due to target being treated as passive
Can anyone help? Thanks in advance.
EDIT: Found a simple solution for anyone looking.
changeScroll(){
let style = document.body.style.overflow
document.body.style.overflow = (style === 'hidden') ? 'auto':'hidden'
}
<div
onMouseEnter={this.changeScroll}
onMouseLeave={this.changeScroll} />
<ReactComponent/>
</div>
Thanks! I was looking for a current answer for managing it.
My ReactJS solution was to add and remove the event when onMouseEnter/Leave is detected. Additionally, with the use of passive, taken from this answer link.
Principal component:
<Wrapper
onWheel={this.handleScroll}
onMouseEnter={this.disableScroll}
onMouseLeave={this.enableScroll}
> ...</Wrapper>
handleScroll():
public handleScroll = (event) => {
if (event.deltaY > 0) {
this.decreaseValue()
} else {
this.increaseValue()
}
}
enableScroll():
public enableScroll = () => {
document.removeEventListener('wheel', this.preventDefault, false)
}
disableScroll():
public disableScroll = () => {
document.addEventListener('wheel', this.preventDefault, {
passive: false,
})
}
preventdefault():
public preventDefault(e: any) {
e = e || window.event
if (e.preventDefault) {
e.preventDefault()
}
e.returnValue = false
}

Cancel drag on key press Angular cdk Drag and Drop

I´m working in a application implementing the new drag and drop from angular material CDK and i´m trying to cancel the drag event of the element pressing Esc, i mean, i start dragging the element but if i press Esc while i´m dragging the element, it should go back to the position from where i start dragging it, so far i haven´t found a way to do this, does anyone know how can i do this. There nothing in the cdk documentation about this any idea. i try doing something like this.
Template
<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let movie of movies" (cdkDragEnded)="onDragEnded($event)" cdkDrag>{{movie}}</div>
</div>
Ts component
onDragEnded(event: CdkDragEnd) {
console.log(event)
event.source.element.nativeElement.style.transform = 'none';
const source: any = event.source;
source._passiveTransform = { x: 0, y: 0 };
}
but no success so far.
I also faced this problem for a long time. Finally I could fix it by dispatching a mouseup event that will act as the user releasing the mouse.
#HostListener('window:keyup', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.key === 'Escape') {
document.dispatchEvent(new Event('mouseup'));
}
}
This is an extremely hacky solution and comes with it's down sides. In fact, you are not cancelling the drag but instead dropping. Meaning that if you are hovering a cdkDropList or one is active it will trigger the cdkDropListDropped emmiter for that list. Something you can easily workaround by adding a flag.
private _canceledByEsq = false;
#HostListener('window:keyup', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.key === 'Escape') {
this._canceledByEsq = true;
document.dispatchEvent(new Event('mouseup'));
}
}
handleDrop() {
if (!this._canceledByEsq) {
// Do my data manipulations
}
}
Hope this helps you... :)
You can move the dragged item to a position using:
event['source']['element']['nativeElement']['style']['transform'] = 'translate3d(0,0,0)';
event['source']['_dragRef']['_activeTransform'] = {x: 0, y: 0};
event['source']['_dragRef']['_passiveTransform'] = {x: 0, y: 0};
The best way to do it is to call event.source._dragRef.reset(); (as #AleRubis mentioned in comment) on ESC key press.
Now the question is from where you can get that _dragRef outside cdkDrag events (ESC key event), you can save it in a component variable like this when drag starts.
Component:
cdkDragStarted = (event) => {
this.dragRef = event.source._dragRef;
}
Template:
<p cdkDrag (cdkDragStarted)="cdkDragStarted($event)">
Draggable paragraph
</p>
Here's a version using rxjs. It requires a reference to CdkDrag as ViewChild. Unfortunately, because there is no public method to stop dragging on the DragRef you have to use dispatchEvent as the only way to end the dragging process.
There are two parts in the example below. What's happening is that the ended event can only be listened to after a start, and that instance of listening can be stopped by a subject triggered by pressing escape.
In the AfterViewInit a subscription is created to the started EventEmitter from the CdkDrag directive.
After the start event, the stream that switches to listening to ended.
If the cancel request is fired, the stream will be ended by the takeUntil operator, and reset() will be called on the directive to reset the position and dispatchEvent() will be used to stop the drag process.
Otherwise once the end event is fired, the onDragEnded() method is called from the OP.
Unless there is some really funniness going on, the ended event will only be fired at most once per start, so there is no need for an additional take(1).
private dragCancelRequest = new Subject();
ngAfterViewInit() {
this.drag.started.pipe(
switchMap(({ source }) => source.ended.pipe(
takeUntil(this.dragCancelRequest.pipe(tap(() => {
source.reset();
document.dispatchEvent(new Event('mouseup'));
})))
)),
tap(x => this.onDragEnded(x))
).subscribe();
}
#HostListener('window:keyup', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.key === 'Escape') {
this.dragCancelRequest.next();
}
}
You can use something like...
#HostListener('window:keyup', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.code === 'Escape') {
// call dragend event
}
}

Effective onBlur for react-data-grid

I'm jumping in on a pretty big React JS project which is using react-data-grid to display a bunch of editable data. Right now, you have to click an Update button to send changes to the server. My task at hand is to create auto-save functionality like so:
User selects cell to edit text
User changes text
User either moves to another cell or clicks away from data-grid
Changes are persisted to the server
Here's what I've tried:
onBlur event on each column. The event will fire, but it seems like the event was attached to a div and not the underlying input control. Therefore, I don't have access to the cell's values at the time this event is fired.
onCellDeselected on the <ReactDataGrid> component itself. It seems like this method is fired immediately upon render, and it only gets fired subsequent times when moving to another cell. If I'm editing the last cell and click away from the data-grid, this callback isn't fired.
Using react-data-grid, how can I effectively gain access to an editable cell's content when the user finishes editing?
The commits on react-data-grid are handled by the EditorContainer. The commit logic is simple. An editor commits a value when:
The editor unmounts
Enter is pressed
Tab is pressed
In some cases when the arrows are pressed (will skip this part is it may not be necessary for you, you can look at the logic for this on the EditorContainer)
Based on that the way I would recommend to do the autosave is:
Create an an EditorWrapper (HOC) the editors where you want auto save to be turned on
const editorWrapper(WrappedEditor) => {
return class EditorWrapper extends Component {
constructor(props) {
base(props);
this._changeCommitted = false;
this.handleKeyDown.bind(this);
}
handleKeyDown({ key, stopPropagation }) {
if (key === 'Tab' || key === 'Enter') {
stopPropagation();
this.save();
this.props.onCommit({ key });
this._changeCommitted = true;
}
// If you need the logic for the arrows too, check the editorContainer
}
save() {
// Save logic.
}
hasEscapeBeenPressed() {
let pressed = false;
let escapeKey = 27;
if (window.event) {
if (window.event.keyCode === escapeKey) {
pressed = true;
} else if (window.event.which === escapeKey) {
pressed = true;
}
}
return pressed;
}
componentWillUnmount() {
if (!this._changeCommitted && !this.hasEscapeBeenPressed()) {
this.save();
}
}
render() {
return (
<div onKeyDown={this.handleKeyDown}>
<WrappedComponent {...this.props} />
</div>);
}
}
}
When exporting you editor just wrap them with the EditorWrapper
const Editor = ({ name }) => <div>{ name }</div>
export default EditorWrapper(Editor);
Use one of the start or stop event callback handlers at the DataGrid level like onCellEditCommit
<DataGrid
onCellEditCommit={({ id, field, value }, event) => {
...
}
/>
or a valueSetter for a single the column definition:
const columns: GridColDef[] = [
{
valueSetter: (params: GridValueSetterParams) => {
// params.row contains the current row model
// params.value contains the entered value
},
},
];
<DataGrid columns={columns} />

Categories

Resources