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} />
Related
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!
I built a filter functionality for a list of banks. It works fine in desktop: When the user puts in any name, the keypress event occurs and later it call the filter() function.
However, it does not work on mobile, since no keypress event is triggered.
The goal is whenever user put any letter in input filed, it should call that filter() function on mobile. Is there any way to do this?
(this website is built on wix so it use its velo api)
let debounceTimer;
export function search_keyPress(event) { //enable onKeypress for input form , search is the id of input
$w("#clearSearch").show(); //show the cross mark to clear inputs
$w("#search").value; // value of input field
if (debounceTimer) {
clearTimeout(debounceTimer);
debounceTimer = undefined;
}
debounceTimer = setTimeout(() => {
filter($w("#search").value); //ID of input form
}, 200);
}
let searchWord;
function filter(search) {
if (searchWord !== search) {
$w("#bankTableDataset").setFilter(wixData.filter().contains('bankName', search)); // ID of the dataset
searchWord = search;
}
}
I have the following class component
...
constructor(props) {
super(props);
...
this.currentlyEditedInput = React.createRef()
}
...
onClick(id, column) {
return (event) => {
...
let { clientX, clientY } = event;
let repeatClick = ( true /*repeat needed*/) ? function() {
let click = new MouseEvent("click", {
clientX,
clientY
});
console.log(this.currentlyEditedInput.current.firstChild.tagName) // INPUT
console.log(this.currentlyEditedInput.current.firstChild.dispatchEvent) // function dispatchEvent()
this.currentlyEditedInput.current.firstChild.dispatchEvent(click) // nothing happens
} : undefined;
...
this.setState(/*new state*/, repeatClick); // when state is updated new input is rendered
...
}
}
...
render() {
...
return (
...
<TableCell
className={classes.cell}
key={column.name}
onClick={ this.onClick(row.id, column) }
>
...
<Input
ref={this.currentlyEditedInput}
autoFocus
...
/>
...
</TableCell>
...
)
}
When a table cell is clicked a new input with some value appears inside it, but the cursor is in the end of the input so the user has to click one more time. I want to make the cursor appear where the user clicks. So I dispatch the same click event in the callback (second argument of setState), but calling dispatchEvent does not seem to change anything.
May be this task should be solved in a completely different way. What is the correct way to do it in React?
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>
)
I am working on a form including a sort of tag input. If a user inputs a tag and hits enter it will add the tag to a certain array. But, when I hit enter, it will also submitting the form. Ofcourse, I can add the e.preventDefault() trick but then again, it will still run the JavaScript code, something I don't want when I am trying to input a tag.
So I've tried to add a if statement to notice if the key is equel to enter but the form don't get notified which button is clicked, I guess.
So this function will run If I hit enter on the form.
handleForm(e) {
e.preventDefault();
// Not working..
if(e.keyCode === 32) {
alert('Enter..') // prevent submitting further here or something
} else {
let state = { ...this.state.product }
if (state.name == '' || state.price == 0 || state.ingredients.length <= 0) {
alert('Naam, prijs en ingredienten zijn verplicht');
} else {
console.log(state);
}
}
}
How can I totally block the enter key for submitting? How can I use that key code for instance with a form or something? I've tried to add a event listener but that didn't work out since it will submit when I hit a other button than Enter.
For context, my tag input function which got fired from a keyup event.
handleKeyPress(e) {
// if the event key == enter key (is working..)
if (e.keyCode === 32) {
// Check if there is a ingredient supplied
if(this.state.tag == '') {
alert('Vul een ingredient in')
} else {
// Get the value of the ingredient input
let tag = this.state.tag;
// Copy state of just the ingredients (not the product)
let ingredients = [...this.state.product.ingredients];
// Create an array including only the names of the ingredients
let names = ingredients.map((item) => {
return item.name;
});
// Check if the array already includes the ingredient
if (names.includes(this.state.tag)) {
// Alert if the ingredient already exists
alert('Deze ingredient is al toegevoegd');
} else {
// Set the ingredient with value
let ingredient = { name: tag, value: 1 };
// Push the ingredient to the ingredients array of product
ingredients.push(ingredient);
// Get the product state
let product = this.state.product;
// set the ingredients of the product object with new ingredient
product.ingredients = ingredients;
// Change and set the state of proudct and empty out the tag input (ingredient)
this.setState({ product: product }, () => {
this.setState({ tag: '' });
});
}
}
}
}
When you use a form, it will always trigger onSubmit event when you hit enter, so assuming you want to use "enter" to keep adding tags, you can leave your add tags code in the submit function and add a button with type="button" (so the button wont submit on clicks) for when you are done with the form and use its onClick event to finish the form.
Example:
constructor(props) {
super(props);
this.handleDoneWithForm = this.handleDoneWithForm.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleDoneWithForm() {
// Code for when the form is finished
}
handleSubmit(event) {
event.preventDefault();
// Add tag code
}
render() {
return (
<form onSubmit={this.handleSubmit}> // will be triggered on enter
// form inputs
<button type="button" onClick={this.handleDoneWithForm}> // will be triggered on click
Done with form
</button>
</form>
);
}