Article

React Inline Styles with the Style Property

Published: 20 Dec 2021 | Last updated 20 December 2021

If we simply try to add inline styles inside the JSX elements we will encounter this error:

 Invariant Violation: The 'style' prop expects a mapping from style properties to values, not a string. For example, `style={{marginRight: spacing + 'em'}}` when using JSX

Let's see an example where we can make use of Inline Styles:

// Functional Component
 
  function App() {
    const date = new Date(2018, 6, 31, 15)
    const hours = date.getHours()
    let timeOfDay
    const styles = {
      fontSize: 30
    }
    
    if (hours < 12) {
      timeOfDay = "morning"
      styles.color = "#04756F"
    } else if (hours >= 12 && hours < 17) {
      timeOfDay = "afternoon"
      styles.color = "#8914A3"
    } else {
      timeOfDay = "night"
      styles.color = "#D90000"
    }
    
    return (
      <h1 style={styles}>Good {timeOfDay}!</h1>
    )
  }
  • Techtud Admin
  • @techtud
  • Senior editor at techtud

What to read next

Sounds rather exhausting, right?Well, it was indeed exhausting! Many of the times but when I analyze what all I was able to accomplish in a year's

Here is a time worthy documentation: