EdG
EdG

Reputation: 2351

setting css specific to element in map function

I am rendering a div multiple times by using map javascript function in my react application. I want to set css (width) of each element. Width will be element specific. I am rendering div like this

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

className of each div is different. How can I set css of each element. For setting width I will be needing {item.time} reference.

I tried setting it in componentDidMount like this

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')

But it didn't work. I am not getting any errors in console.

Upvotes: 0

Views: 3582

Answers (2)

bennygenel
bennygenel

Reputation: 24660

You can use style prop for styling components.

{
    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>)
    })
}

Upvotes: 0

Chris
Chris

Reputation: 59491

There are a few issues with your code:

  1. You are using the same id for each item in the array. IDs need to be unique.
  2. The idea of css classes are to select multiple similar elements and not to have a unique class for each element.
  3. If you re-arrange the items in the array, the css-class for the moved items will change.

That said, you could do apply an 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 prevents you from defining person_timeline.length number of classes in your css.

Upvotes: 1

Related Questions