Search code examples
javascriptcssreactjsstyles

How to change a single property of a style component already created using conditional rendering


I got the following code:

function App() {
...
const [message, setMessage] = useState(false);

const styles = {
  backgroundColor:'lightGray',
  ...
}

  return (
         <div>
           <h1> style:{notification ? styles:{styles.backgroundColor:'red'}}>Test</h1>
         </div>
   ) 
}

What I am trying to achieve is just changing the backgroundColor property of the already created style.


Solution

  • function App() {
    ...
    const [message, setMessage] = useState(false);
    
    const styles = {
      backgroundColor:'lightGray',
      ...
    }
    
      return (
             <div>
               <h1> style={notification ? {...styles, backgroundColor: 'red'} : styles}>Test</h1>
             </div>
       ) 
    }