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
の引数には行の情報が入ってきます。)
参考