Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object is possibly 'undefined' when using array values with styled-components

I’m building a Skeleton component that accepts a prop called circleSizes, which is an array of numbers to set the width and height of the Skeleton.

This is the component:

export const SkeletonHandler: React.FC<SkeletonHandlerProps> = ({
  count = 1,
  circle = false,
  circleSizes = [50, 50],
}) => {
  return (
    <SkeletonWrapper count={count} circleSizes={circleSizes}>
      <Skeleton count={count} circle={circle} />
    </SkeletonWrapper>
  );
};

My types.ts:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export type SkeletonHandlerProps = {
  count?: number;
  circle?: boolean;
  circleSizes?: Array<number>;
};

I know that if I remove the ?, the error will go away but I don’t want this property to be required.

And my styled-components file:

export const SkeletonWrapper = styled.div<SkeletonHandlerProps>`
  width: ${(circle) => (circle ? 'fit-content' : '100%')};
  ${({ circle, circleSizes }) =>
    circle &&
    css`
      .react-loading-skeleton {
        width: ${circleSizes[0]};
        height: ${circleSizes[1]};
      }
    `}
`

Image error: enter image description here

What I have tried:

  1. Putting a default value for the circleSizes array at props, e.g: circleSizes = [50, 50]
  2. Putting a default value on types.ts, e.g: circleSizes?: Array<number> | [50, 50];
  3. Converting circleSizes to number on the styled-components file, e.g: width: ${Number(circleSizes[0])};

What I’m doing wrong?

>Solution :

it complains because you are using the brackets operand on a variable that might be undefined so try adding a validity check before circleSizes && circleSized[1]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading