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:

1function MyInputBox() {
2
3  const myStyle = {}
4  
5  return (
6    <input type="text" style={myStyle}
7  )
8  
9}

We can then conditional rendering with Boolean variables and ternary operators (within the CSS object) to create different styles, depending on those Boolean variables:

1function MyInputBox() {
2
3  const darkMode = true
4  const spaceyMode = true
5  
6  const myStyle = {
7    backgroundColor: darkMode ? 'black' : 'white',
8    color: darkMode ? 'white' : 'black',
9    padding: spaceyMode ? '30px', '10px', 
10    border: '1px', 
11    cursor: 'pointer'    
12  }
13
14  return (
15    <input type="text" style={myStyle} />
16  )
17    
18}

Note how here we have to use CSS-in-JSX as we cannot use JavaScript in a CSS file!

⬅️ older (in textbook-react)
⚛️ React list rendering
newer (in textbook-react) ➡️
Deploying React apps to GitHub pages ⚛️
⬅️ older (in code)
⚛️ React list rendering
newer (in code) ➡️
Deploying React apps to GitHub pages ⚛️
⬅️ older (posts)
⚛️ React list rendering
newer (posts) ➡️
Metcalfe's law 🛜