LoginSignup
1
2

More than 1 year has passed since last update.

MUI(Material UI)のDataGridで特定の行にstyleを追加する方法【React】

Last updated at Posted at 2023-02-02

ReactのUIフレームワークであるMUI(Material UI)のDataGridにて、特定の行にだけstyleを設定する方法を解説していきます。
指定のセルが入力されている時に行(row)の色を変えるなどの実装に役立つかと思います。

React・MUI(DataGrid)の実際のコード

import { Container } from '@mui/material'
import { DataGrid, GridColDef, GridRowParams } from '@mui/x-data-grid'

const Home = () => {
  const columns: GridColDef[] = [
    { field: 'id', headerName: 'ID' },
    { field: 'name', headerName: 'NAME' },
    {
      field: 'email',
      headerName: 'E-MAIL'
    }
  ]

  const rows = [
    {
      id: 1,
      name: 'Taro',
      email: 'test1@gmail.com'
    },
    {
      id: 2,
      name: 'Ken',
      email: 'test2@gmail.com'
    },
    {
      id: 3,
      name: 'Yui',
      email: 'test3@gmail.com'
    }
  ]

  return (
    <Container>
      <DataGrid
        columns={columns}
        rows={rows}
        checkboxSelection
        // クラスを設定しておく
        sx={{
          '& .rows-active': {
            background: '#2C7CFF !important'
          }
        }}
        // 特定の条件でclassを返す
        getRowClassName={(params: GridRowParams) => {
          if (params.id === 2) {
            return 'rows-active'
          }
          return ''
        }}
      />
    </Container>
  )
}

export default Home

DataGridのgetRowClassNameで特定の行にのみclassを設定することができます。
そのclassにstyleを当てておくことで、特定の行(row)にのみstyleを当てることが可能です。
上記の例では、idが2の行のみ背景が変化するようにしています。(※getRowClassNameの引数には行の情報が入ってきます。)

mui.png

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2