Home > front end >  Object is possibly 'undefined' when using array values with styled-components
Object is possibly 'undefined' when using array values with styled-components

Time:02-03

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:

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?

CodePudding user response:

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]

  •  Tags:  
  • Related