Tips for styling an array of objects using mapping techniques

I have an array of messages and I am currently using the map() function. Each message in the array has two keys - one for the author and another for the message content. What I want to achieve is to change the styles of the div tag when displaying the last message. How can I accomplish this? Specifically, while mapping through the messages array, if the current element being mapped is the last one, I would like to add a div with modified styles (such as adding shadow or changing background focus on that specific div tag). Can you guide me on how to do this?

Code:

 <div id="messages" className="card-block">
                            {this.state.messages.map((message, index) => {

                                if(message.author === this.props.match.params.user){
                                    return (
                                        <div key={index} className="msgBoxRight"><p className="msgTextRight">{message.message}</p></div>
                                    )
                                }else{
                                    return (
                                        <div key={index} className="msgBoxLeft"><p className="msgTextLeft">{message.message}</p></div>
                                    ) 
                                }  
                            })}
                        </div> 

Screenshot of chat app:

https://i.stack.imgur.com/JcTXn.png

Essentially, I wish to apply different styles to the latest message in the chat box, such as giving it a background focus or a box shadow. How can I achieve this effect?

Answer №1

Here's a simple solution using the css selector ":last-child":

.block .message {
  background-color: #ff0000
}

.block .message:last-child {
  background-color: #00ff00
}
<div class="block"> 
  <div class="message">message </div>
  <div class="message">message </div>
  <div class="message">message </div>
  <div class="message">last message</div>
</div>

Answer №2

The correlation between the variables index and length in an array can be expressed as:

index = length - 1 

By using this formula, you can determine which element in the array is the last one:

if (index + 1 === length) {
  // Apply your own custom styling here
}

Why not give it a shot?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I make an absolutely positioned div slide down from a specific area on the page using jQuery's slideDown() function?

I have a website project in progress where the main image on the homepage is of a house with windows and a door. The idea is that when a user clicks on a window, a <div> should appear with some text. Similarly, clicking on the door should trigger a & ...

Displaying the URL of a link on the screen using jQuery

I am looking for a solution to add a link address after the link itself in a table containing reference links for our staff. I have used CSS to achieve this in the past, but the address was not copyable by users. Instead, I am interested in using jQuery&ap ...

Why is the reference of `this` pointing to `o` in this scenario (o.method)() rather than the global object?

Let's consider the scenario with an object: var o = { prop: 3, method: function() {return this.prop} } My expectation was that calling (o.method)() would result in undefined, but instead it returned 3, indicating that the reference of this ...

What causes a globally declared array to remain empty in the global scope even after data is pushed to it within a callback function?

Initially, I set an empty array as the value for the global variable artistURLs. Then, within the Cheerio .each() iterator method, I push strings (stored in the local variable artistURL) into the artistURLs array. var request = require('request&apos ...

The button on my page refuses to align in the center, and I'm at a loss as

Struggling to center a button within my div, despite having all other content centered. Here is my code: .middle { width: 100%; height: auto; text-align: center; position: relative; ...

Tips for utilizing dynamic imports with a named export in Next.js

I created a new react component that is functioning perfectly for me. import { Widget } from 'rasa-webchat'; function CustomWidget(){ return ( <Widget initPayload={"payload"} socketPath={"/socket.io/ ...

Is there a way to access the value of a variable within a loop inside a function and store it in a global variable?

I am struggling to retrieve the value of a variable after it has passed through a loop. I attempted to make it a global variable, but its value remains unchanged. Is there any way to achieve this? Below is my code snippet where I am attempting to access t ...

sending data from a callback to an express router

As I embark on learning node.js, I've encountered a challenging issue. In my passportAuth.js file, I create a user and have a callback to ensure the user is created successfully. The code snippet looks something like this: req.tmpPassport = {}; var ...

Conceal a row depending on the value in a specific column

After reviewing the data in the table provided: +-----------------------+-----------------+---------------+ | 212 | fred | red | +-----------------------+-----------------+---------------+ | 230 ...

Choose all the inputs with the value attribute specified

How can I select all input textboxes in my form that have the required class and no value using jQuery? Currently, I am using: $('input[value=""]', '.required') The issue I am facing is that even when a user enters a value in the text ...

Puppeteer with Typescript: Encountering issues during the transpilation process

The issue stems from the fact that I am unable to use Javascript directly due to Firebase Functions Node.JS version lacking support for Async/Await. As a workaround, I have converted the code into Typescript and am currently attempting to transpile it to c ...

Prevent Scrolling on Body with W3 CSS

While implementing scroll body lock packages like body-scroll-lock, react-scrolllock, or tua-body-scroll-lock alongside the W3 CSS package, I have encountered an issue where the body remains unlocked even when the designated element is active or open (e. ...

What seems to be the issue with this basic Node.js function not functioning properly?

I'm attempting to utilize a function that returns a boolean answer and then verifying it using if-else statements. function checkDNS(domain, tld) { var dns = require('dns'); dns.lookup(domain+'.'+tld, function (err, addres ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...

What is the best way to prevent a jQuery hover event from adding a text-shadow to the CSS?

Currently, I am facing an issue with a jQuery event that triggers a text-shadow effect: $(".leftColumn").hover(function (){ $(".leftColumn h2").css("text-shadow", "0px 2px 3px rgba(0, 0, 0, 0.5)"); },function(){}); The problem arises when the text-shad ...

Guide for creating a scroll-triggered rotation animation using only JavaScript

Looking to achieve a cool scroll effect with an image that rotates on the X-axis by a specific degree, such as 70deg. The goal is to have the image's rotateX value change to 0deg when it enters the viewport upon scrolling and revert back to 70deg whe ...

Transform the size and convert an object from a picture into text based on the user's scrolling

I've been intrigued by the scrolling effects used on websites like Google SketchUp and Google Plus. It's fascinating how elements can transform as you scroll down the page. For example, on Google SketchUp's site, the banner starts off integr ...

Use React-table to store the value of an accessor in the state while also utilizing a

I am currently working on implementing a checkbox table using react-table. The primary objective is to have checkboxes in the first column, and upon selection of a checkbox, I intend to store the ID defined in the accessor in the state. Despite going thro ...

The content momentarily flashes on the page during loading even though it is not visible, and unfortunately, the ng-cloak directive does not seem to function properly in Firefox

<div ng-show="IsExists" ng-cloak> <span>The value is present</span> </div> After that, I included the following lines in my app.css file However, the initial flickering of the ng-show block persists [ng\:cloak], [ng-cloak], ...

Excessive HTML and CSS overflow stretching beyond the boundaries of the page on the right

It seems like the issue lies with div.ü and div.yayın, as they are causing overflow on the right side of the page. When these elements are removed, the overflow issue goes away. Are there different positioning codes that can be used to prevent this? d ...