React conditional styling
changing the look of the React app based on certain criteria
// updated 2025-05-15 12:25
In React, we can use conditional rendering methods to output different styles depending on dynamic data.
Boolean variables and ternary operators
For example, let us consider an input box:
function MyInputBox() {
const myStyle = {}
return (
<input type="text" style={myStyle}
)
}
We can then conditional rendering with Boolean variables and ternary operators (within the CSS object) to create different styles, depending on those Boolean variables:
function MyInputBox() {
const darkMode = true
const spaceyMode = true
const myStyle = {
backgroundColor: darkMode ? 'black' : 'white',
color: darkMode ? 'white' : 'black',
padding: spaceyMode ? '30px', '10px',
border: '1px',
cursor: 'pointer'
}
return (
<input type="text" style={myStyle} />
)
}
Note how here we have to use CSS-in-JSX as we cannot use JavaScript in a CSS file!