Home > Software design >  using properties from same object conditionally
using properties from same object conditionally

Time:10-10

Just a simple question, but really confusing me a lot. I have an object, which contains all the styles I want to apply to an element in my reactApp.

const LinkStyle = {
    textDecoration : 'none',
    color : 'rgba(58, 62, 65, 1)',
    '&:hover' : {
    backgroundColor : 'rgba(238, 240, 243, 1)'
    },
    mx : {lg : 2, md : 2, sm : 2, xs : 2},
}

I am applying this to my component as

<SomeDOMelememt style={({condition}) => condition ? LinkStyle : (LinkStyle)   'border-radius : '20px''} />

I mean, rather than making an entirely different object for case, when '!condition', i want to reuse the 'LinkStyle' object only, just want to add some additional properties to the same object so as to match the two different scenes. I don't want to create a separate object or adding more (conditional style properties) to my <SomeDOMElement/>

CodePudding user response:

You can conditionally add the property to your styling:

const LinkStyle = {
    textDecoration : 'none',
    color : 'rgba(58, 62, 65, 1)',
    '&:hover' : {
    backgroundColor : 'rgba(238, 240, 243, 1)'
    },
    mx : {lg : 2, md : 2, sm : 2, xs : 2},
    ...(condition && ({'border-radius' : '20px'}))
}
<SomeDOMelememt style={LinkStyle} />

CodePudding user response:

You can use the spread operator ... like this, which fills in every key from an object:

<SomeDOMelememt 
  style={
    ({condition}) => condition ? LinkStyle : {'border-radius': '20px', ...LinkStyle} />
  • Related