Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically change class based on current index in a react component. (object.map)

I have this Object.map statement in a react component.

{
  instagramItems.map((item, index) => (

    <div className="row" Key={index}>
      <div onClick={() => handleClick(item, index)} className="image-block col-sm-4" style={{
        backgroundImage: "url(" + item.media_url + ")",
        backgroundPosition: 'center ',
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat'
      }}></div>

I want to change the col-sm-X class on a div so the out put repeats this pattern.

col-sm-4

col-sm-8

col-sm-4

col-sm-4

col-sm-4

col-sm-8

col-sm-4

I’m guessing I need to use the Index to calculate what I need to set the class to.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yep. If it has logic behind it, i.e. "item 2, and second from last" are 8, then you can code that in.

`col-sm-${index === 1 || index === myArray.length-2 ? 8: 4}`

Or, you could have a separate array of classes if they follow no pattern and pull the loop index.

const cols = [4, 8, 4, 4, 4, 8]
const myArray.map((x, i) => <div className={cols[i]}></div>)

How you go about it is more of a developer experience kind of thing. What pattern is easiest to understand/maintain/etc

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading