babukuinha
babukuinha

Reputation: 29

Change a especify css element inside a loop in react

I'm trying to make a calendar and I want to select some of the first columns in the first line of the table and change their css . Is there a certain method where I can select the element by his key?

import React from 'react'

export default function Calendario() {

 const lines = Array.from(Array(5).keys());
 const columns = Array.from(Array(7).keys());

 return(
        <div>
            <table>
              <tbody>
                {lines.map((linha) => (
                  <tr key={linha}>
                  {columns.map((coluna) => (
                  <td
                  key={coluna}
                >test</td>
              ))}
            </tr>
            ))}
            </tbody>
        </table>
        </div>
    );  
}

Upvotes: 0

Views: 45

Answers (1)

abnaceur
abnaceur

Reputation: 262

You can try this and change the style as you see fits.

import React from 'react'

export default function Calendario() {

 const lines = Array.from(Array(5).keys());
 const columns = Array.from(Array(7).keys());

 return(
        <div>
            <table>
              <tbody>
                {lines.map((linha, idx) => (
                  <tr key={linha}>
                  {columns.map((coluna) => (
                  <td style={ idx === 1 ? {backgroundColor: "blue"} : {null}}
                  key={coluna}
                >test</td>
              ))}
            </tr>
            ))}
            </tbody>
        </table>
        </div>
    );  
}

EDITED :

Well to handle many colums you can use TypedArray.prototype.includes() method.

import React from 'react'

export default function Calendario() {

 const lines = Array.from(Array(5).keys());
 const columns = Array.from(Array(7).keys());
 const columnsNum = [1, 2, 5];

 return(
        <div>
            <table>
              <tbody>
                {lines.map((linha, idx) => (
                  <tr key={linha}>
                  {columns.map((coluna) => (
                  <td style={ columnsNum.includes(idx) ? {backgroundColor: "blue"} : {null}}
                  key={coluna}
                >test</td>
              ))}
            </tr>
            ))}
            </tbody>
        </table>
        </div>
    );  
} 

Upvotes: 1

Related Questions