How to add background color to a specific cell of a grid on cell selection in vaadin 23

I want to add a grid in vaadin screen in which i will be selecting multiple cells and on cell selection i want to add background color to that selected cell.

I have created a grid using below code snippet

Grid<String[]> grid = new Grid<>();

Random random = new Random();
List<String[]> data = new ArrayList<>();
for (int i = 0; i < rows; i++) {
    String[] rowData = new String[columns];
    for (int j = 0; j < columns; j++) {
        rowData[j] = String.valueOf(random.nextInt(100)); // Generate random value
    }
    data.add(rowData);
}

for (int i = 0; i < columns; i++) {
    int index = i; // Java 8+ requires effectively final variables in lambda expressions
    grid.addColumn(row -> row[index]);
}

grid.setItems(data);
add(grid);

One way that pops into my mind right now (given that you can select rows with grid, but not individual cells) is to render a component that allows interaction. It could be something as simple as a Div, with a click listener that would send the current selection status to the server and it would react by changing the style class so it gets painted with a special background color.
You could use this cookbook recipe for the styling.

1 Like

Depending on the use case, you can add a button or checkbox to the cells that can be selected.

If you use div, make sure to give it the proper ARIA roles so it’s accessible:

You can use the utility classes to add a background color to a container: