Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
How to Create 2D Grid by Repeating a Component certain times in a Loop in reactJS?

I am Working on Movie Ticket Booking Website. I Want to make a Grid Layout of 4x7. So What i Thought is i would Create a button Component and repeat it in Loop Several Times.

Pseudo Code:

for(var i=0;i<4;i++){
    for(var j=0;j<7;j++){
        button Component();
    }
    newline Component();
}

But this type of thing is not supported in reactjs. So What Can i Do for Implementation of above thing? Also When a button is clicked i want to change its color for that i have given ID to button Component so i can do it by DOM Manipulation but how to do that using UseState?

EDIT: I am done with array part but what about Color Change now? I Tried DOM but it returns NULL

CODE:

const items=[];
    for(let i=1;i<=20;i++){
        let style={
            backgroundColor:"White"
        };
        items.push(<button className="btn btn-danger" onClick={()=>changeColor(i)} style={style} id={"button"+i}/>);
    }
    function changeColor(index) {
        document.getElementById("index").style.backgroundColor="Green";
    }
This Thing returns NULL i Do not know why
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Using direct DOM manipulation is not recommended, you should instead leverage the reactive render cycle that React provides.

Here is a snippet which declares a Button component that handles its own internal state as an example. Mutiple Buttons are rendered inside a map() in the parent, and each button then controls its own active state.

const { useState } = React;

function App() {
  return (
    <div>
    {[1,2,3].map(n =>(
      <Button key={n} label={'Button' + n} />
    ))}
    </div>
  )
}

function Button({label}) {
  const [active, setActive] = useState(false);
  
  const handleClick = (e) => {
    setActive(a => !a);
  };
  
  return (
    <button 
      type='button' 
      className={active ? 'active' : ''} 
      onClick={handleClick}
    >
    {label}
    </button>
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
.active {
  background-color: tomato;
}
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id='root'></div>

But generally buttons will be used to interact directly with the parent's state, in which case the click handler and state logic will be declared in the parent, with relevant properties being passed down to the children.

const { useState } = React;

function App() {
  const [buttons, setButtons] = useState([
    {id: 1, label: 'Button 1', active: false}, 
    {id: 2, label: 'Button 2', active: false}, 
    {id: 3, label: 'Button 3', active: false}]);

  const handleClick = (buttonId) => {
    setButtons(buttons => buttons.map(b => 
      b.id === buttonId
        ? {...b, active: !b.active}
        : b));
  };

  return (
    <div>
    {buttons.map(b =>(
      <Button key={b.id} id={b.id} label={b.label} onClick={handleClick} active={b.active}  />
    ))}
    </div>
  )
}

function Button({label, id, onClick, active}) {
  
  return (
    <button 
      type='button' 
      onClick={() => onClick(id)}
      className={active ? 'active' : ''}
    >
    {label}
    </button>
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
.active {
  background-color: tomato;
}
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id='root'></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda