From de9cc14b2cc83f97a3af49dd021f1c0c6a6f4158 Mon Sep 17 00:00:00 2001 From: Matheus Wichman Date: Wed, 12 Jul 2023 18:06:17 -0300 Subject: [PATCH] [docs] Add paragraph about managing focus of custom edit components --- .../data-grid/editing/CustomEditComponent.js | 14 ++++++++------ .../data-grid/editing/CustomEditComponent.tsx | 14 ++++++++------ docs/data/data-grid/editing/editing.md | 16 ++++++++++++++-- 3 files changed, 30 insertions(+), 14 deletions(-) diff --git a/docs/data/data-grid/editing/CustomEditComponent.js b/docs/data/data-grid/editing/CustomEditComponent.js index 92c4832ac8a77..8762b22fec6d8 100644 --- a/docs/data/data-grid/editing/CustomEditComponent.js +++ b/docs/data/data-grid/editing/CustomEditComponent.js @@ -1,6 +1,7 @@ import * as React from 'react'; import Box from '@mui/material/Box'; import Rating from '@mui/material/Rating'; +import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils'; import { DataGrid, useGridApiContext } from '@mui/x-data-grid'; function renderRating(params) { @@ -8,24 +9,25 @@ function renderRating(params) { } function RatingEditInputCell(props) { - const { id, value, field } = props; + const { id, value, field, hasFocus } = props; const apiRef = useGridApiContext(); + const ref = React.useRef(); const handleChange = (event, newValue) => { apiRef.current.setEditCellValue({ id, field, value: newValue }); }; - const handleRef = (element) => { - if (element) { - const input = element.querySelector(`input[value="${value}"]`); + useEnhancedEffect(() => { + if (hasFocus && ref.current) { + const input = ref.current.querySelector(`input[value="${value}"]`); input?.focus(); } - }; + }, [hasFocus, value]); return ( ) { } function RatingEditInputCell(props: GridRenderCellParams) { - const { id, value, field } = props; + const { id, value, field, hasFocus } = props; const apiRef = useGridApiContext(); + const ref = React.useRef(); const handleChange = (event: React.SyntheticEvent, newValue: number | null) => { apiRef.current.setEditCellValue({ id, field, value: newValue }); }; - const handleRef = (element: HTMLSpanElement) => { - if (element) { - const input = element.querySelector( + useEnhancedEffect(() => { + if (hasFocus && ref.current) { + const input = ref.current.querySelector( `input[value="${value}"]`, ); input?.focus(); } - }; + }, [hasFocus, value]); return ( { + if (hasFocus) { + ref.current.focus(); + } + }, [hasFocus]); const handleValueChange = (event: React.ChangeEvent) => { const newValue = event.target.value; // The new value entered by the user apiRef.current.setEditCellValue({ id, field, value: newValue }); }; - return ; + return ; } ```