Dynamically Changing the Background Color of a Grid Row in v23

Hi All,

In v23, I’m attempting to change the background color of certain grid rows based on a condition for those rows. The code snippet I’m using, based around Spans, isn’t producing the desired result. My project is here. The snippet looks like this:

@Route
@CssImport("./styles/styles.css")
public class MainView extends VerticalLayout {

    public MainView() {
        Grid<Person> grid = new Grid<>(Person.class);
        grid.setItems(getPeople());

        Label lblHiya = new Label("What's going on, folks?");
        grid.setItemDetailsRenderer(new ComponentRenderer<>(person -> {
            Span span = new Span(person.getName());
            if (person.getName().equalsIgnoreCase("John Doe")) {
                span.addClassName("blue-background-row");
            }
            return span;
        }));
        lblHiya.addClassName("red-bold-text");

        add(grid, lblHiya);
    }

The results I’m seeing looks like this:




For starters, I have to click onto a row to see anything highlighted, and then, I only see the name repeated with the desired background color. Is there a way in v23 to get the whole row highlighted in this color without needing to click the row?

Why are you using a details renderer if you wanna add/style columns? (Use grid.addColum())

Here’s an example on how you can set the background color How do I set grid row background color dynamically - Vaadin Cookbook

That did it!! Thank you!!

1 Like

I found that snippet in another forum and was trying it. Paola’s cookbook fix got it working.