Home > Back-end >  how we can add style tag on a div in react
how we can add style tag on a div in react

Time:03-09

I am working in React. Now I want to add some new functionality of dark mode and night mode. I want to add some style on a div but It gives some problems. the code of div style is :

<div className="container" style={`{backgroundColor :   ${props.mode === "light" ?"white" : "black"}}`}>

now anyone can give the concept that how I can use the style tag for a div.

CodePudding user response:

style expects you to pass it an object, not a string:

<div 
  className="container"
  style={{
    backgroundColor: props.mode === "light" ? "white" : "black"
  }}
>

CodePudding user response:

you're close! Inline CSS in React is written like a javascript object. This means you need double curly braces around the style block, and only the stuff on the right side of the colon needs to be a string.

<div 
  className="container" 
  style={{
    backgroundColor: props.mode === 'light' ? 'white' : 'black'
  }}
>

CodePudding user response:

You should use object, instead of string

const bgColor = props.mode === "light" ? "white" : "black";
<div className="container" style={{ backgroundColor: bgColor }}>
  • Related