Home > Mobile >  How to access to tag style with React.js
How to access to tag style with React.js

Time:06-27

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?

CodePudding user response:

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

CodePudding user response:

you don't have to change the styles with javascript you can just add media query to your styles, for your target devices like:

/* this is for tablets */
@media only screen and (min-device-width: 768px){
    #number1{
        background-color: 'red';
    }

}

CodePudding user response:

You could write class .backgroundRed and just use condition classes like:

className={width > breakpoint ? '.backgroundRed' : '.elseClass'}

or you can directly write styles with style attribute:

style={condition ? {backgroundImage: 'red'} : {} }

CodePudding user response:

In this case you have different solutions, but if you want to dynamically change some element style, you can do the following by using the state to store a style object.

function MyComponent(props) { 
   // Save your style object in the state
   const [style, setStyle] = useState({background: 'white'});

   // Then just call setStyle when you want to update your style
    
   // I.E. Something like this:
   useEffect(() => {
     window.addEventListener('resize', function () {
          setStyle({...style, background: 'red'});
     })
   }, [])

   // And bind the style to the target element
   return (
     <div style={style}>
        My Content
     </div>
   )
}

This is speaking of react and element style.


In your specific situation, where you want to react to screen size, perhaps a css media query approach would be more efficient.

  • Related