How to figure out the coordinates of an element in react
2 min readOct 16, 2020
The other day I wrote a substantial amount of nigh unreadable code to figure out where exactly each element in a grid sat on the screen.
updateInvaderCoordinates = () => {let position = this.state.fleetPositionlet newImage = this.state.altImagelet screenHeight = window.innerHeightlet screenWidth = window.innerWidth//figured it out! my margins are set to viewheight, not viewwidth.// let margin = screenWidth * .4let margin = screenHeight * .4let fleet = document.getElementById('fleetContainer')let spaceInvaders = document.getElementsByClassName('SpaceInvader')let coordinates = []for (let i = 0; i < spaceInvaders.length; i++){let invaderHeight = spaceInvaders[i].clientHeightlet fleetLateral = fleet.clientLeftlet invaderVertical = spaceInvaders[i].offsetTop// console.log(screenHeight - invaderVertical + invaderHeight/2)let invaderLateral = spaceInvaders[i].offsetLeft// console.log(spaceInvaders[i].id)let invaderWidth = spaceInvaders[i].clientWidth//I need to detect the lower and upper updates based on the fleet's vertical position in the state.let invaderLower = screenHeight - invaderVertical - invaderHeight -this.state.fleetVertical//need to update lower and upper coordinates in the same way I did left and right: factoring in the fleet container.let invaderUpper = screenHeight - invaderVertical - this.state.fleetVerticallet invaderLeft = margin + fleet.offsetLeft + spaceInvaders[i].offsetLeftlet invaderRight = invaderLeft + invaderWidth/2coordinates.push({top: invaderUpper, left: invaderLeft, right: invaderRight, bottom: invaderLower, id: parseInt(spaceInvaders[i].id)})}return coordinates}
Today, I learned “Object.getClientRects()” does exactly the same thing. I could condense all of it to something much simpler. Something like:
let spaceInvaders = document.getElementsByClassName('SpaceInvader')let coordinateArray = []for (let invaderCount = 0; invaderCount < spaceInvaders.length; invaderCount++){let invader = spaceInvaders[invaderCount]let coordinates = invader.getClientRects()coordinateArray.push({bottom: coordinates[0].bottom, left: coordinates[0].left, right: coordinates[0].right, top: coordinates[0].top, id: `invader${invaderCount}`})}
return coordinateArray
}
Ah well.
Ever tried. Ever succeeded. No matter. Try again. Succeed again. Succeed better.