Home > Blockchain >  Use object to map color to component React
Use object to map color to component React

Time:02-20

I am trying to create a reusable tag component and based on company will apply the correct background and text color.

const colorMapping = {
  facebook: "white"
}

const backgroundMapping = {
  facebook: "blue"
}

export const App = (props) => {
   return (
       <div style={{ backgroundColor: "", color: "" }}>
       {props.company} //Facebook
       </div>
   )
}

How can I apply the color based on the based string? and Is this the right approach, could I just use 1 mapping object?

CodePudding user response:

How can I apply the color based on the based string? let say this.props.company name is the base string,right? if its so then you can do something like this

style={{ backgroundColor: backgroundMapping[this.props.company], color: colorMapping[this.props.company] }}

but,wait

Is this the right approach, could I just use 1 mapping object? no,then why?what if there is no color for given this.props.company? so you code may need to check first that for given company name mapping found,and of course you should use single mapping instead of two, then how? consider the steps create a theme object like this

const theme={
       facebook:{color:"while",background:"blue"},
       defaultTheme:{
            color:"while",background:"black"
        }
 }

and then you can assign this theme to your component as following

 <div style={theme[this.props.company]||theme.default}>
   {props.company} //Facebook
   </div>
  • Related