0

I'm trying to style a list of items in React, with a specific styling for the last item of this list.

Here is what I have for the moment

const SuggestionStyles: CSSProperties = {
  borderBottom: '1px solid #ccc',
};
// ...
{suggestions.map((suggestion: GeocodingSuggestion) => {
  return(
    <p style={SuggestionStyles} key={suggestion.name}>{suggestion.name}</p>
  );
})}

So not using any particular library to handle the styling right now. And I can't manage to find how to target the last child within SuggestionStyles

Axiol
  • 5,664
  • 9
  • 37
  • 49

2 Answers2

0

Change style={SuggestionStyles} to:

style={suggestions.indexOf(suggestion) === suggestions.length - 1 ? SuggestionStyles : null}

Zunayed Shahriar
  • 2,557
  • 2
  • 12
  • 15
0

There are 2 options:

  1. Use the :last-child selector, something like:

    .container > p:last-child {
      color: red;
    }
    <div class="container">
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
      <p>Paragraph 3</p>
    </div>
  2. We can use the current index of map() to check if we're at the last element and apply any css accordingly:

    {suggestions.map((suggestion, index) => {
      const style = (index === suggestions.length - 1) ? { borderBottom: '1px solid #ccc' } : '';
      return(
        <p style={style} className={className} key={suggestion.name}>{suggestion.name}</p>
      );
    })}
    

    If you've already got a styling object, we can merge them with the new one:

    const style = (index === suggestions.length - 1) ? {...defaultStyling, ...{ borderBottom: '1px solid #ccc' } } : defaultStyling;
    
0stone0
  • 34,288
  • 4
  • 39
  • 64