Roy
Roy

Reputation: 29

How to modify the code to not get appendchild error

I have been trying to use the below code but whenever I am trying to run it in react file I am getting this error "Uncaught TypeError: Cannot read properties of null (reading 'appendChild')" error . At first I found a design from codepen, then I tried to integrate it in react code but error is enevitable Thus I am in need of finding answer to it

const container = document.getElementById('container');
const circlesArr = [];

for(let i=0; i<15; i++) {
    circlesArr[i] = [];
    for(let j=0; j<15; j++) {
        const circle = document.createElement('div');
        circle.classList.add('circle');
        container.appendChild(circle);
        circlesArr[i].push(circle); 
    }
}
function growCircles(i, j) {
    if(circlesArr[i] && circlesArr[i][j]) {
        if(!circlesArr[i][j].classList.contains('grow')) {
            circlesArr[i][j].classList.add('grow');
            setTimeout(() => {
                growCircles(i-1, j)
                growCircles(i+1, j)             
            }, 100)         
            setTimeout(() => {
                circlesArr[i][j].classList.remove('grow');
            }, 300);
        }
    }
}
circlesArr.forEach((15, i) => {
    cols.forEach((circle, j) => {
        circle.addEventListener('click', () => {
            growCircles(i, j);
        });
    });
});
  return (<div id="container" className="container"></div>)}

The CSS code

.container {
    display: flex;
    flex-wrap: wrap;
    width: 450px;
}
.circle {
    background-color: #5295F1;  
    height: 14px;
    width: 14px;
    transition: transform 0.3s linear;
}
.circle.grow {
    transform: scale(2);
}

Upvotes: 0

Views: 81

Answers (1)

Avet Brutyan
Avet Brutyan

Reputation: 306

I assume the code before return is inside your component's body. It means you are trying to get an element with id "container" before rendering it so at that point the document.getElementById('container') returns null which doesn't have appendChild method.

Upvotes: 1

Related Questions