Home > Net >  If/Else if/Else Ternary
If/Else if/Else Ternary

Time:11-10

I am trying to do some coniditonal styling in react js. Very new to react, so there may be a better way to do this, but have searched the internet to no avail. I am trying to check the screen size and style based off of said screen size. In this use case I am wanting to center some text based off of screen size. Can someone please tell me if there is a better way to do this? This is not working for me currently.

Edit: Placed some logs in there and what it is doing exactly is when the page loads "textAlign" is not applied to the element at all even though the screen size is > 993px. Once I shrink the screen down to < 993px and > 578px is applies the "textAlign: center" to the element and then once it shrinks down < 578px it does not set it back to none. It keeps it centered.

const styles = {
    footerColOne:{
        textAlign: deviceSize > 993 ? "none" : (deviceSize < 993 && deviceSize > 578) ? "center" : "none",
        paddingLeft: deviceSize < 993 ? "26px" : "80px",
        paddingTop: deviceSize < 993 ? "28px" : "63px",
    },
    footerColTwo:{
        textAlign: deviceSize > 993 ? "none" : (deviceSize < 993 && deviceSize > 578) ? "center" : "none",
        paddingLeft: deviceSize < 993 ? "26px" : deviceSize < 578 ? "51px" : "50px",
        paddingTop: deviceSize < 993 ? "40px" : "86px",
    },
  }

I am then calling that style like this

<Col lg={3} style={ styles.footerColOne }>

Any help is greatly appreciated.

CodePudding user response:

media query will be good fit here.

@media screen and (min-width: 578px) and (max-width: 993px) {
  .someclass {
   text-align:center;
  }
}

@media screen and (max-width: 993px) {
  .someclass {
   text-align:center;
   padding-left:26px;
   padding-right:28px;
  }
}

@media screen and (min-width: 993px) {
  .someclass {
    text-align:left /* none as you wanted. /*;
  }
}

So given,

max-width all the styles inside this media query will be applied if screen size is below this max-width.

min-width all the styles inside this media query will be applied if the screen size is greater than the min-width.

CodePudding user response:

const getDevice = (deviceSize) => 
    deviceSize < 993 
        ? (deviceSize < 993 && deviceSize > 578) 
            ? 'tablet'
            : 'mobile'
        : 'web'


const footerColOne = {
    'web': () => {
        return {
            textAlign: 'none',
            paddingLeft: '26px',
            paddingTop: '28px'
        }
    },
    'tablet': () => {
        return {
            textAlign: 'center',
            paddingLeft: '80px',
            paddingTop: '63px'
        }
    },
    'mobile': () => {
        return {
            textAlign: 'none',
            paddingLeft: '80px',
            paddingTop: '63px'
        }
    }
}


footerColOne[getDevice(deviceSize)]()


  • Related