Thaarik
Thaarik

Reputation: 63

Changing font size with respect to the change in screen resolution using styled-components in react

I'm designing a simple react app using styled components. I'm trying to make it more responsive.

So I created a component(Ad) with props values of width and height. Depending upon the width and height values, the font size should change.

This is how made my Ad component.

const AdContainer = styled.div`
  max-width: ${props=>props.width};
  max-height:  ${props=>props.height};
`;  

const Adp = styled.p`
      font-size:  ${props=>props.width>"870px"?"24px":"16px"};
    `;

function Ad({height,width}) {
  return (

    <AdContainer height={height} width={width}>
         <AdTitle>Hello</AdTitle>
    </AdContainer>

    );
}

Consider this parent component

function ProductPage() {
  return (
    <>
<Ad width={"1920px"} height={"600px"}/>
    </>
  );
}

export default ProductPage;

When we pass width=1920px and height=600px, the font size of Adtitle should change into 24px because of this

const Adp = styled.p`
      font-size:  ${props=>props.width>"870px"?"24px":"16px"};
    `;

But it is not changing and sticks to 16px.

What can I do to rerender this component whenever the screen size changes?

Or is there any other alternatives to solve this so that wherever I use this Ad component, the font size should change with respect to the given props width and height value?

Upvotes: 1

Views: 2131

Answers (1)

Ivan Popov
Ivan Popov

Reputation: 696

You are trying to compare string to string as numbers. Do not do like this. Do it like this.

const Adp = styled.p`
  font-size:  ${p => p.width > 870 ? "24px" : "16px"};
`;
// And pass the props like this
<Adp width={1920} height={600}/>
// AdContainer
const AdContainer = styled.div`
   max-width: ${p => `${p.width}px`};
   max-height:  ${p => `${p.height}px`};
`; 

Upvotes: 1

Related Questions