creating custom styling for elements within a map function

Within my React application, I am using the map JavaScript function to render a div multiple times. Each element needs to have a specific width set via CSS. The className for each div is unique. Here is how I am rendering the divs:

{this.props.face_clicked_reducer.person_timeline.map((item, i) => (
    <div className={`marker-item-${i}`} id="sele1"></div>
))}

I need to adjust the width of each element based on {item.time}. I attempted to do this in componentDidMount like so:

this.props.face_clicked_reducer.person_timeline.map((item, i) => (
    $("<div className={`marker-item-${i}`}></div>").css({
        "width": ((item.endTime - item.startTime) * (100/this.props.player_time_update_reducer.video_duration)) + '%',
        "left": ((item.endTime) * (100/this.props.player_time_update_reducer.video_duration)) + '%'
    })
)).css('backgorund', 'red');

Unfortunately, this approach did not work as expected and no errors were reported in the console.

Answer №1

Several issues have been identified in your code:

  1. Using the same id for each item in the array, which should be unique.
  2. The purpose of CSS classes is to apply styles to multiple similar elements, not to assign a unique class to each element.
  3. When rearranging items in the array, the CSS class for moved items will change.

However, you can consider using inline styling instead:

this.props.face_clicked_reducer.person_timeline.map(
  (item, i) => <div style={{width: (50 * i) + "%", height:(20 * item.time) + "%"}}></div>
);

Alternatively:

this.props.face_clicked_reducer.person_timeline.map(
  (item, i) => {
    let s = {
      width: (50 * i) + "%",
      height: (20 * item.time) + "%"
    };
    return <div style={s}></div>;
  }
);

This approach helps avoid creating a large number of classes based on person_timeline.length in your CSS.

Answer №2

To apply styles to components, you can utilize the style prop.

{
this.props.face_clicked_reducer.person_timeline.map((item, i) => {
const style = {
width: ((window.innerWidth * 0.2) * i),
height: ((window.innerHeight * 0.2) * item.time)
}
return (<div className={`marker-item-${i}`} style={style}></div>)
})
}

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

Chart Vue, Component

I am currently working with a chart implemented using vue-chart. I am facing a challenge where I need to populate the mydata array with data retrieved from the store.js file. I want to automatically push this data into the mydata array without the need for ...

Reduce the dimensions of a CSS attribute automatically

Displayed below is the image with a width of 192 and height of 109: <a href="https://www.blogger.com/u/1/blogger.g?blogID=4402911157743442948#"><img alt="" class="thumbnail" height="109" src="https://2.bp.blogspot.com/-E5ftfbCCgkw/XjnLpO347cI/AAA ...

Having trouble with my React private route, can't seem to get it to function properly

I'm fairly new to React, and I've set up a private route with an authToken passed through props from the state of App.js. The idea is that if the authToken is true, the private route should direct me to /HomePage, but whenever I log in with valid ...

Transitioning images with jQuery

For my college project website that focuses on selling music, I have implemented a buy button that resembles the one seen on Apple's app store. You can view the images of the button here: View Image 1 View Image 2 I am wondering if anyone is famili ...

Displaying items as objects in search results in Kendo Angular's auto complete feature

Seeking assistance with implementing Kendo Angular's auto complete widget using server filtering. Following the service call, the popup displays [object Object] and the count of these matches the results retrieved from the server. Could someone kindly ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

Encountering an issue while attempting to utilize the .find() method in Mongoose

Currently, I am in the process of setting up a database using MongoDB and integrating the Mongoose ODM with Node.js. After running the code multiple times without any issues, I encountered an unexpected error when adding the last block to utilize the .find ...

What is the best way to eliminate a component from a group using Jquery/Javascript before attaching it to a different component?

I am working with a group of dynamically added buttons and need to prepend a selection to an existing controlgroup. Here is a glimpse of what I am dealing with: $elements = [a.midToggle, a.menuToggle, a.ui-crumbs] Before prepending, I want to make sure t ...

How can I use jQuery to pinpoint where my focus currently lies and debug any issues?

Triggering focus() on an element is a simple task, but after encountering debugging problems, I've come to realize that finding out where my focus has shifted can be quite challenging. The issue arises when I'm creating a modal window using jq.UI ...

Changing the position of a Bootstrap popover dynamically from top to bottom

Struggling with the bootstrap popover here. I can't seem to change the popover position from top to bottom when it reaches the top of the viewport. I attempted to use placement: 'auto bottom' but unfortunately, it didn't do the trick f ...

Searching for substrings in NodeJS using Express

In this code snippet, I am using Express JS and AES256 encryption to encode and decode simple text strings with a predefined key. The Express JS web server is set up to display specific elements based on the URL content. For instance, if the URL was abc. ...

Understanding the complexities of asynchronous programming in node.js

I'm struggling to grasp the concept of asynchronous code in Node.js. Below, you'll find two versions of my code. My first attempt consists of three functions: a processing function (iim), a file copy function (fse.copy), and an archive function ...

Despite making changes, the React Element continues to be rendered

I am a beginner in React and facing an issue with my simple app My aim is to implement a search functionality, but the problem arises when I search for an element - all search results are displayed After clearing the search box, all elements appear as in ...

Creating dynamic HTML elements with bound JSON data

When a JSON array list of objects is retrieved from the database, it is sent to the client side upon page load of the current user control. var json = new JavaScriptSerializer(); var jsonList = json.Serialize(mylList); Page.Client ...

The divs contained are misaligned and not properly centered on the page

My container div contains 6 inner divs, but they are not properly centered on the page. Although the divs are equally spaced apart, they seem to be shifted to the left. I tried using 'justify-content: center' without success, and I suspect it mi ...

What could be the reason for the gtag event not showing up in Google Analytics?

Here is an example of my script: <html> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxxxxxxx-1"></script> <script> wi ...

Guide to dividing the screen into three horizontal sections

I am currently working on a website and trying to divide a page into three different sections: one for the title and a button, one for the content, one for the text input. . The issue I'm facing is that the divs are not filling the height and ...

How come my invocation of (mobx) extendObservable isn't causing a re-render?

Can't figure out why the render isn't triggering after running addSimpleProperty in this code. Been staring at it for a while now and think it might have something to do with extendObservable. const {observable, action, extendObservable} = mobx; ...

Is it possible to create two custom WP queries that both use the same 'rand' parameter with the 'orderby' set to 'rand'?

My homepage currently displays 9 posts with a "Load More" button that fetches another 9 posts using ajax. The posts are ordered by date, but I want to change the order to random. However, when I use orderby rand in two wp_query instances, the second query ...

Incorporating Distinct Items into an Array with JavaScript

There is a Filter object that stores information about different Car Types. The data is fetched via AJAX calls - on the first call, objects 0-10 are created and added to an array. Subsequent calls bring more car types which are also appended to the array. ...