Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - 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>
    );  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...