Home > Back-end >  Can you render react component to div with display none?
Can you render react component to div with display none?

Time:12-17

I need to render react component to div with id hover-countdown. So as the name says it is not visible when page load, but only on hover. Does this somehow affect ReactDOM render? Because i am not able to render it. Is there some other way? Thank you:)

const HoverCountdown = () => {

  return (
    <span>Countdown</span>
  );
};

document.addEventListener("DOMContentLoaded", () => {
  ReactDOM.render(
    <HoverCountdown />,
    document.getElementById("hover-countdown")
  );
});

CodePudding user response:

Does this somehow affect ReactDOM render?

Not really. It React only concerns itself with DOM updates.

If the element it renders inside is display: none then the React rendering process will generate the DOM inside that element.

Then, subsequent to the React rendering, the browser will convert the DOM to something rendered on screen (which will be nothing because the container is display: none).

CodePudding user response:

If you set the visibility to hidden, hovering over the invisible component will not trigger the :hover styles to take effect.

What is odd is that if you inspect element and toggle the :hidden styles then it will properly show up.

const HoverCountdown = () => (
  <span>Countdown</span>
);

//document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <HoverCountdown />,
    document.getElementById('hover-countdown')
  );
//});
.wrapper {
  background: #EFE;
}

#hover-countdown {
  visibility: hidden; /* will render fine if removed */
}

#hover-countdown:hover {
  visibility: visible;
  color: #040;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div >
  <div id="hover-countdown"></div>
</div>

  • Related