bier hier
bier hier

Reputation: 22520

How can I loop through all the elements in my reactjs component?

I have a reactjs component that looks something like this:

<div className="wrapper">
                <div className="box box1" ref="04"/>
                <div className="box box1" ref="03"/>
                <div className="box box1" ref="02"/>
</div>

In reality there are 25 nested divs I just listed 3. Question is how can I loop through these elements so I can change the className property for all of them?

Upvotes: 2

Views: 193

Answers (2)

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

You could do something like the following:

const Example = () => {
   const newArr = [...Array(25)]; 
   return (
       <div>
        {
          newArr.map((i, index) => {
            return (
              <div key={index} className={`box${index}`}>{index}</div>
            )
          })
        }
      </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 2

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

Use JSX

<div className="wrapper">
   {
      [...Array(25)].map((un, index) => (
          <div key={index} className={yourClassName} ref={yourRef} />
        )
      )
   }
</div>

Upvotes: 2

Related Questions