0

I'm doing my first typescript project. This function is from a javascript vanilla project I did before, but when I use react-typescript I'm getting this error on both innerHTML from the function:

TypeError: Cannot set property 'innerHTML' of null

 function callGames() {
    let bets = document.getElementById('bets-container-lotos');
    bets!.innerHTML = '';
    const games = gamesJson.length;
    for (let i = 0; i < games; i++) {
      bets!.innerHTML +=
        '<Loto id="bets-color-' +
        i +
        '" value="games' +
        i +
        '" OnClick={(' +
        i +
        ') => whichGameIs}>' +
        gamesJson[i].type +
        '</Loto>';
      let changeColor = document.getElementById('bets-color-' + i);
      if (changeColor) {
        changeColor.style.color = gamesJson[i].color;
        changeColor.style.borderColor = gamesJson[i].color;
      } else {
        console.log('Cant find the id bets-color-' + i);
      }
    }
  }

const newBet: React.FC = () => {
 return (
        <LotoContainer id='bets-container-lotos'>
        </LotoContainer>)
}
4
  • What guarantees document.getElementById('bets-container-lotos') is there by the moment when you call it? bets!.innerHTML = ''; <- what's the point to cheat and use !. here? Commented Aug 20, 2021 at 3:01
  • 1
    This isn't actually recommended in React, but you can still do it. Another thing that you should remember is that React uses VirtualDOM instead of actually keeping the element in the DOMTree, so it's possible that the element might not have been rendered on screen when you have tried getElementById Commented Aug 20, 2021 at 3:02
  • zerkms, i know that is not the point of typescript, i did a if(bets) before using ! but im trying to solve that error first Commented Aug 20, 2021 at 3:06
  • Samridh Tuladhar, maybe its that. Im doing a React.useEffect(() => {}, [callGames()]); Commented Aug 20, 2021 at 3:07

2 Answers 2

1

Use the useref hook instead and do this

 <LotoContainer id='bets-container-lotos' ref=bets>

And this

const bets=useRef(null)
bets.innerHTML=“” 
Sign up to request clarification or add additional context in comments.

Comments

1

Becasue document.getElementById can return an element or null. So you need to check bets before use it.

if(bets){
  bets.innerHTML = '';
}

Comments

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.