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

axios.delete does not fully remove the item permanently

I am working on a basic react app which allows users to add contacts to a list using mysql. However, I am facing an issue with my delete function as it is not permanently removing the item from the list. After setting my data, I tried adding a timeout to c ...

The gauge created dynamically using the justgage plugin does not display the value

I am currently experimenting with dynamically adding gauges, and although they are displayed on the screen, the values being shown are incorrect. Even when the graph indicates a different value, it still displays 0. These gauges are triggered by an onclick ...

jQuery: Track mouse movement with a delay

I'm looking to create a div that follows cursor movement with a slight delay, similar to the effect seen on this website: In the example link provided, you can observe that the 'follower' has a brief delay in its animation. I attempted to ...

Ways to ensure a video completely fills the frame

I am experiencing an issue where the video in the main div of my home page does not fully fill the div right away - I have to refresh the page for this to happen. As a result, there is black space on the left and right sides. Interestingly enough, this pr ...

Creating a Like button using react.js

How can I make only the selected button change, instead of all at the same time when clicked? I have implemented a function that includes a Boolean state and toggles it const [like, setLike] = useState(false); const handleLike=()=> { setLike(! ...

How can we convert props into state once they have been initialized using GetDerivedStateFromProps?

Presented here is a straightforward Component design: export default class Editor extends Component { constructor(props) { super(props); this.state = { field: "Some Initial Text" }; this.handleChangeField = this.handleChangeField.bind(this ...

Error message: "AngularJS encountered a $injector:modulerr error in Internet Explorer 11."

I've successfully created an AngularJS App that functions properly on most browsers like Firefox, Opera, Safari, Edge, and Chrome. However, there seems to be a compatibility issue with IE 11. When attempting to open the app in IE 11, the following er ...

What is the best way to create an impact?

Need help fixing the parallax effect on this page. I attempted to implement a parallax effect but encountered some issues. Here is the JavaScript code: $objWindow = $(window); $('section[data-type="background"]').each(function(){ var $bgOb ...

Determining the true width of a span element using jQuery

I am trying to determine the actual width of a span element within a div, but when I attempt to do so, it gives me the width of the entire div instead. Here is the code I am working with: <div class="content"> <span class="type-text" id="ta ...

What could be causing my ajax file uploader to malfunction?

I am currently working on building an AJAX file upload module. Below is a snippet of the code I have been using: //creating a form for uploading files via AJAX FileUploader.prototype.createForm = function() { // creating a new form var form = docu ...

Troubleshooting Tips for Node.js and MongoDB Socket Closure Issue

I'm running into an issue while working on the login system for my NodeJS application. Everytime I attempt to retrieve a collection, MongoDB throws me this unusual error. The Error Message [MongoError: server localhost:27017 sockets closed] name: &a ...

"Seamless responsiveness in design with jQuery, but encountering compatibility issues

My usage of jQuery is quite basic to ensure that elements are properly positioned when they are moved: function ipad() { var width = jQuery(window).width(); if (width < 1200 && width >= 768){ //if tablet jQuery('.mobbut').css(&apo ...

Shopping cart with Redux implemented in React.js

Why do I encounter an issue where clicking "Add to cart" only registers a single change even after multiple clicks, and the item doesn't get added to the cart? How can this be resolved? The desired functionality is for the 'cart' array to st ...

The properties are not appearing on the screen nor in the React Development Tools

Having difficulties grasping React props and mapping data from an array? Struggling to get the props to show up on your Card component, or display in React dev tools? It's unclear where the mistake lies. Seeking assistance to pinpoint the issue. Also ...

Implementing Ajax Js to search within a specific div - reducing text overload on the page

Our e-shop on Prestashop requires an Ajax search feature to find compatible batteries and adapters on the page. Here is the code I have created: https://jsfiddle.net/fgfjo2n9/ I am facing two issues: • 1st I want the output to only display the heading ...

Refreshin the attached DOM to a directive without a page reload

Within a directive, I have implemented some text and a video tag in the code below: app.directive('ngAzuremediaplayer', function () { return { restrict: 'AE', priority: 10, link: function (scope, elem, attr ...

Encountered an error while trying to generate the Component class for the ColorlibStepIcon from Material UI in TypeScript

I am trying to convert the ColorlibStepIcon functional component into a class component for my Stepper. Unfortunately, I have not been successful and keep encountering errors. I have attempted some changes but it is still not working as expected. You can ...

Is it possible to create a QR Code using Ionic 5?

Is there a way to generate QR Codes in Ionic 5? I attempted it, but keep receiving an error stating that the qrcode element is not recognized. Here is my code: qrcode.html <ion-item> <ion-input type="text" placeholder="My QR d ...

The concept of the "Centering Effect" refers

Check out the code I have below: http://jsfiddle.net/G8Ste/577/ I want the effect to expand in all directions, not just to the right and bottom. I've experimented with margin: 0, auto, and other CSS and HTML styles to center it, but nothing seems t ...

Tips for retaining input field content within a BootstrapVue table

Below is a BootstrapVue table I'm working with; The code, courtesy of this response, is showcased below; new Vue({ el: '#app', data() { return { filter: '', items: [ { id: 1, first_name: "Mikkel&qu ...