-1

have just a question if it's possible to increment className in React JS???

to do something like that :

/* in first file */
const rowCount = 68;

class PhotosItem extends Component {
  constructor() {
    super();
    this.list = Array(rowCount).fill().map((val, idx) => {
      return {
        value : 0
      }
    });
  }

  render() {
    return (
      <>
        {this.list.map(this.renderRow)}
      </>
    );
  }

  renderRow(item) {
    return (
      <article class="photo__item">
        <PhotosFigure />
      </article>
    );
  }
}

export default PhotosItem;
/* in other file */
class PhotosFigure extends React.Component{
  render (){
    return (
     <>
       <div className={`figure photo_{* HERE AN INCREMENT *}`}></div>
     </>
     );
  }
}

export default PhotosFigure;

I want a render like this :

<article class="photo__item">
  <div class="figure photo_1"></div>
</article>

<article class="photo__item">
  <div class="figure photo_2"></div>
</article>

[...]

<article class="photo__item">
  <div class="figure photo_68"></div>
</article>

Have you an answer for me ? or better way to do that?

thks.

(I'm French so I'm really sorry if I made a mistake in English)

Guss411
  • 26
  • 3
  • 1
    Class names are strings. Concatenation of two strings is what you gotta do. One string is the name, the other is the index. – Victor Apr 22 '20 at 22:48

1 Answers1

0

The second parameter is the index of the array for the map function. Therefore, you can change you renderRow function to this and pass the index as a prop.

  renderRow(item, index) {
    return (
      <article class="photo__item">
        <PhotosFigure index={index+1} />
      </article>
    );
  }

Then inside your PhotosFigure component, you can receive the index as a prop and apply styles to your class like this:

class PhotosFigure extends React.Component{
  render (){
    return (
     <>
       <div className={`figure photo_${this.props.index}`}></div>
     </>
     );
  }
}

Rohit Kashyap
  • 1,553
  • 1
  • 10
  • 16