Home > OS >  document.getElementById('id').style.display = 'none', Cannot read properties of
document.getElementById('id').style.display = 'none', Cannot read properties of

Time:03-09

I am importing a SVG as a react component (Dog1), some elements in the SVG need to be hidden so in order to do this i use document.getElementById('id').style.display = 'none' for all the ids of the elements that need to be hidden. This works some of the time and seems to be random if the SVG will load correctly on my react page. Sometimes it doesnt work and gives me the error TypeError: Cannot read properties of null (reading 'style').

I think this is probably because the document is actually getting the whole page opposed to just the SVG component, is there anyway i can fix this so that i get the SVG component?

my code is below (the forloops are used as a way to get multiple ids and set to none)

import { ReactComponent as Dog1 } from '../images/dog-chart-treatments.svg'


function NewChart() {

  function svgDog(Dog1){
    console.log(Dog1)
    console.log(document.getElementById("treatment-tooth-408"))

    for (let i = 401; i< 410; i  ) {
      var fourZeroValue = `treatment-tooth-{}`.replace(/{}/, i)
      console.log(fourZeroValue, document.getElementById(fourZeroValue))
      document.getElementById(fourZeroValue).style.display = 'none'
    }
    for (let i = 101; i< 110; i  ) {
      var oneZeroValue = `treatment-tooth-{}`.replace(/{}/, i)
      document.getElementById(oneZeroValue).style.display = 'none'
    }
    for (let i = 301; i< 310; i  ) {
      var threeZeroValue = `treatment-tooth-{}`.replace(/{}/, i)
      document.getElementById(threeZeroValue).style.display = 'none'
    }
    for (let i = 201; i< 210; i  ) {
      var twoZeroValue = `treatment-tooth-{}`.replace(/{}/, i)
      document.getElementById(twoZeroValue).style.display = 'none'
    }

  }

  svgDog(Dog1) 

    return (<div>


        <h1>Big Dog test</h1>
        <div className='displayChart'>
          <h4>Dog</h4>
          <hr></hr>
          <div className='image-gray'>
            <Dog1></Dog1>
          </div>
        </div>
      
        </div>

        
   
    );
  }
  
  export default NewChart;

CodePudding user response:

When you are calling document.getElementById() the elements you are trying to find aren't rendered yet, try to use "useEffect"

Code inside this hook will run only when finished rendering

https://reactjs.org/docs/hooks-effect.html

CodePudding user response:

Try this:

First assign it using variable:

let element1 = document.getElementById('id')

Next, check for it:

if (element1) {
   element1.style.display = "none"
}
  • Related