Search code examples
emotion

Mapping mapping level to background color in Emotion


I have a series of log lines, with corresponding levels in the set {verbose,debug,info,warning,error,fatal}

I'd like to map each level (based on the data of the line I'm rendering) to a colour. What's a nice way of expressing this in emotion?


Solution

  • You could use themes for that. Install the theming package:

    yarn add emotion-theming
    

    Here is a an example with React.

    App.js:

    import React from 'react'
    import ReactDOM from 'react-dom'
    import { ThemeProvider } from 'emotion-theming'
    
    import LogEntry from './LogEntry .js'
    
    const theme = {
      color: {
        severity: {
          verbose: 'pink',
          debug: 'blue',
          info: 'teal',
          warning: 'orange',
          error: 'red',
          fatal: 'darkred',
        }
      }
    }
    
    class App extends React.Component {
      render() {
        return (
          <ThemeProvider theme={theme}>
            <LogEntry severity="info">Info :)</LogEntry>
            <LogEntry severity="warning">Warning!</LogEntry>
          </ThemeProvider>
        )
      }
    }
    

    LogEntry.js:

    /** @jsx jsx */
    import { jsx } from '@emotion/core'
    import styled from '@emotion/styled'
    
    const LogEntry = styled.div`
      color: ${props => props.theme.color.severity[props.severity]};
    `
    
    export default LogEntry;