Home > Enterprise >  How to use @media to change width in prop styled components
How to use @media to change width in prop styled components

Time:11-26

I am not sure if what they called but I have a component which takes its style as an object with its props.

const PricingSection = ({
    secDesc,
}) => {

    return (
        <Text
            {...secDesc}
            content={intl.formatMessage({ id: 'packages.description' })}
        />
    );
};


PricingSection.propTypes = {
    secDesc: PropTypes.object
};

PricingSection.defaultProps = {
    secDesc: {
        width: '50%',
        m: 'auto',
        textAlign: 'center',
        pt: '20px',
        color: '#6a7a8d',
        lineHeight: '1.5rem',
    },
}

I want to apply different witdh for mobile devices. I know how to use @media tag in css but I dont know where to write @media in this component or how achieve what I want.

CodePudding user response:

Instead of passing style object, it would be better if you apply a class to the component for easy maintenance. It'll also solve your problem for width for different size devices as you can add media query for the class in its css file.

Another suggestion would be to use styled-components. They provide great support for adding media queries inside the component file.

Refer:styled-components

CodePudding user response:

you can use 'react-device-detect' and pass the different width from parent component like this:

enter code here
import isMobile from 'react-device-detect'
secDesc: {
   width: isMobile ? '50%' : 'your value',
   m: 'auto',
   textAlign: 'center',
   pt: '20px',
   color: '#6a7a8d',
   lineHeight: '1.5rem',
 }
 < PricingSection 
    secDesc={secDesc}
  />
  • Related