Reputation: 874
When I place one of MUI's Text Field components inside the column header of a Data Grid component, I'm unable to type a space into the text field. Similarly, if I press the right or left arrow key while the text field has focus, the text field loses focus rather than changing the position of the cursor within the text field.
Sandbox: https://codesandbox.io/s/cant-add-space-to-muis-textfield-erpvc?file=/src/App.js
import React from "react";
import { DataGrid } from "@mui/x-data-grid";
import TextField from "@mui/material/TextField";
import "./styles.css";
export default function App() {
const rows = [
{ id: 1, "Column 1": 1, "Column 2": 2 },
{ id: 2, "Column 1": 3, "Column 2": 4 },
{ id: 3, "Column 1": 4, "Column 2": 5 }
];
const createColumn = (name) => {
return {
field: name,
align: "center",
editable: true,
sortable: false
};
};
const columns = [
createColumn("Column 1"),
createColumn("Column 2"),
{
field: "Add a split",
width: 225,
sortable: false,
renderHeader: (params) => {
return (
<TextField
placeholder="Enter column name"
size="small"
onKeyDown={(event) => console.log("Key down: ", event.key)}
onKeyUp={(event) => console.log("Key up: ", event.key)}
onKeyPress={(event) => console.log("Key press: ", event.key)}
/>
);
}
}
];
return (
<div className="App">
<DataGrid
className="App-data-grid"
rows={rows}
columns={columns}
disableSelectionOnClick
disableColumnMenu
/>
</div>
);
}
Upvotes: 11
Views: 4088
Reputation: 1009
I had similar luck with just adding event.stopPropagation() to the DataGrid onCellKeyDown prop. This works generally for any renderCell.
((_cell, event) => {
if (event.KeyCode === 32) event.stopPropagation
Upvotes: -2
Reputation: 81096
In the accessibility portion of the documentation, you can find keyboard navigation details for the data grid. Arrow keys are used to navigate between cells and space (among other things) is used to navigate to the next scrollable page. You can find the handling of those keys in the handleCellNavigationKeyDown function in useGridKeyboardNavigation.ts.
When a key down event happens for one of those special navigation characters, MUI calls event.preventDefault()
which in your case prevents the key from having its default effect within the input. You can prevent that by using event.stopPropagation()
within the TextField onKeyDown
such that the event never reaches the grid's keyboard navigation handling code. Keep in mind though that by doing this, you may be harming some of the keyboard accessibility features.
Here's a modified version of your sandbox demonstrating this: https://codesandbox.io/s/cant-add-space-to-muis-textfield-33joy?file=/src/App.js:863-902.
Upvotes: 16