0

I like to know how I can create this grid in reactJs or vanila javascript?

I have tried to use nth-child but it only works with odd or even numbers or specific child.

enter image description here

1

2 Answers 2

1

You can do something like this, this will work for 3x5 but you can Color however you want, For doing this you need a div style as grid in order to get them in that order.

const createTable = (blue,yellow,red)=>{
  let x = 3;
  let y = 5;
  const grid = document.getElementsByClassName('mygrid')[0]
  for(let i = 0;i<x;i++){
    var div = document.createElement('div')
    div.classList.add('createdDiv')
    grid.appendChild(div)
    for(let z=1;z<y;z++){
     var div = document.createElement('div')
     div.classList.add('createdDiv')
      grid.appendChild(div)
    }
  }
  
  let allDivs = document.getElementsByClassName('createdDiv');
  [...allDivs].forEach((el,i)=>{
    if((i+1)%x==1&&(i+1)/x >= y-blue){
      el.classList.toggle('blue')
    }else if( (i+1)%x==2 && ((i+1)/x) >= y-yellow ){
      el.classList.toggle('yellow')
    }else if((i+1)%x==0 && ((i+1)/x)> Math.abs(red-y)){
      el.classList.toggle('red')
    }
      
  })
  
  
}

createTable(4,1,3)
.mygrid{
  display:grid;
  grid-template-columns: 33.3% 33.3% 33.3%;
}

.mygrid > div{
  border:1px solid #666;
  padding:20px;
  text-align:center;
}

.blue{
  background-color:#33f;
}
.yellow{
  background-color:yellow;
}
.red{
  background-color:red;
}
<div class="mygrid">
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Try with my new answer where you can select by number the child you want...
0

What about this one?

document.querySelector(".mygrid > div:nth-child(2)").style.backgroundColor = "red";
document.querySelector(".mygrid > div:nth-child(4)").style.backgroundColor = "blue";
.mygrid{
  display:grid;
  grid-template-columns: 33.3% 33.3% 33.3%;
}

.mygrid > div{
  border:1px solid #666;
  padding:20px;
  text-align:center;
}

.blue{
  background-color:#33f;
}
.yellow{
  background-color:yellow;
}
.red{
  background-color:red;
}
<div class="mygrid">

  <div style="grid-column:1/-1;">1</div>
  <div >2</div>
  <div class="">3</div>
  <div class="">4</div>
  <div class="">5</div>
  <div class="">6</div>
  <div class="">7</div>
  <div class="e">8</div>
  <div class="">9</div>
  <div class="">10</div>
  <div class="">11</div>
  <div class="">12</div>
  <div class="">13</div>
</div>

1 Comment

thanks but it needs to be dynamic so column 1 (blue) someone could choose 2 instead of 4. your solution is hardcoding the class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.