Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access to tag style with React.js

I want to change the background color by changing the page width by conditionally writing, but to do this I need to be able to access the styles

If we wanted to write this code in JavaScript, it would be like this:

document.getElementById("number1").style.backgroundColor="red";

But what if we want to write this code with React and functional method?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would suggest you to do that with css code by simply using media-query.

#number1 {
 @media screen and (min-width: _yourBreakpoint_) {
    background-color: "red";
  }
}

Docs: https://www.w3schools.com/css/css3_mediaqueries_ex.asp

However If you want to dynamically change the style via react you can use the style prop of the element. Supposing that the element is a div you can simply do:

<div style={{ backgroundColor: width > breakpoint && "red" }}></div>

Docs: https://reactjs.org/docs/dom-elements.html#style

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading