1

I have a loader set up in a div that I want to remove once a certain component is loaded by react. This div exists in my index.html file out side of my components. The code for my div is:

<div class="loaderBackground">
   <div class="loader"></div>
</div>

I've tried using refs, but everything I have found seems to imply that the element would need to be in a component, which I would like to avoid.

Is it possible to remove the element without putting it in a component or do I have to fit in my components somewhere?

2
  • 1
    Can you just use CSS to display:none? Commented Nov 8, 2019 at 14:59
  • To do it from react find element using document.get....().style.display = none; Commented Nov 8, 2019 at 15:01

3 Answers 3

5

I would strongly discourage using document.querySelector().. rather I would you React refs or state as said in the second answer but I would use conditional rendering as it doesn't impact styles which might have different states depending on other stuff

  this.setState({ hide: true });


  <div class="loaderBackground">
       {!hide && <div class="loader"></div>}
  </div>
Sign up to request clarification or add additional context in comments.

2 Comments

I get the impression they're talking about a loader that's outside of the react app scope. With that said, I agree, they should probably put it inside of the react scope and do it this way. But it seems they explicitly don't want to do that.
Reading the question again I agree, still as you said I think it would be better to move it inside react scope and avoid using slow DOM API as it negates React performance features
2

componentDidMount() should be a good place to put your logic.

var element = document.querySelector('.loader');
element.parentNode.removeChild(element);

// or

element.style.display = 'none';

4 Comments

there is no OnComponentDidMount as life cycle methods in react.
@G.aziz it's componentDidMount. I tried to edit this answer with that fixed but it isn't accepted yet.
i approved sorry i didn't see it
Thanks guys. Didn't see that.
2

I propse to add a state that change to true after the loading to control the display of your DOM.

Example:

this.setState({ hide: true });

<div class="loaderBackground">
       <div class="loader" style={{display: hide? "none":"block"}}></div>
</div>

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.