what prop should i use for formatting phone number field in mui data grid react js?

44 views Asked by At

well,in pure html i used pattern attribute for input field, but now i don't have any input field. what should i do? can you give me a reference in mui doc? this is my datatable

const columns = [
    {
      field: "first_name",
      headerName: "First Name",
      width: 180,
      editable: true,
      
    },
    {
      field: "last_name",
      headerName: "last Name",
      width: 180,
      align: "left",
      headerAlign: "left",
      editable: true,
    },
    {
      field: "phone",
      headerName: "phone",
      width: 180,
      editable: true,
      // pattern: "[0-9]{3}-[0-9]{3}-[0-9]{4}",
    },
    
  ];
1

There are 1 answers

0
Krzysztof Krzeszewski On

The GridColDef interface allows for passing a custom renderEditCell parameter, so you can pass any parameter you want to the udnerlying component

function CustomEditComponent(props: GridRenderEditCellParams) {
  return <input type="text" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" value={props.value} onChange={...} />;
}

const columns: GridColDef[] = [
  {
    field: "phone",
    headerName: "phone",
    editable: true,
    renderEditCell: (params: GridRenderEditCellParams) => (
      <CustomEditComponent {...params} />
    ),
  },
];

However it's a little more complicated than that, because the new value has to be passed to the API.

function CustomEditComponent(props: GridRenderEditCellParams) {
  const { id, value, field, hasFocus } = props;
  const apiRef = useGridApiContext();

  const handleValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.value; // The new value entered by the user
    apiRef.current.setEditCellValue({ id, field, value: newValue });
  };

  return <input type="text" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" value={value} onChange={handleValueChange}  />;
}