1

I have this code for example:

interface Props {
  children: any,
  className?: string,
  marginTop?: number,
  marginBottom?: number,
}

const Div = styled.div`
  ${(props: Props) => { return css`
      flex:1;
      ${props.marginTop && "margin-top: " + props.marginTop + "px;"};
      ${props.marginBottom && "margin-bottom: " + props.marginBottom + "px;"};
    `; 
  }}
`;


export const Column: React.FC<Props> = ({ children, className marginTop, marginBottom }) => {
  return (
    <Div className={className} marginBottom={marginBottom} marginTop={marginTop}>
      {children}
    </Div>
  );
};

Now I have to declare the props twice, once in Props and once in the exported component.

Is there a way to make all defined Props available as props for the component?

Just to make it clear, this is the part I'm trying to save my self to write again:

({ children, className marginTop, marginBottom })
3
  • 2
    You don't have to destructure props, if you don't want to. Commented Feb 21, 2022 at 21:30
  • But then i won't be able to use those props on the component. isn't it? Commented Feb 21, 2022 at 21:32
  • 1
    No that isn't it. You can access them on the object, props.marginTop etc. Commented Feb 21, 2022 at 21:33

1 Answer 1

2

If you need to have access to all props (such as passing all of them down to a child component or a styled component), then as what Jon suggested: do not destructure them as arguments. Instead, you can destructure it in the function body instead, if that is what makes you feel makes your code a little more readable:

export const Column: React.FC<Props> = (props) => {
  const { children } = props;
  return (
    <Div className="Column" {...props}>
      {children}
    </Div>
  );
};

This is no different than the old school way:

export const Column: React.FC<Props> = (props) => {
  return (
    <Div className="Column" {...props}>
      {props.children}
    </Div>
  );
};

p/s: For the purpose of typing, it might make sense to define the props type directly on your styled component, i.e. const Div = styled.div<Props>:

const Div = styled.div<Props>`
  ${(props) => { return css`
      flex:1;
      ${props.marginTop && "margin-top: " + props.marginTop + "px;"};
      ${props.marginBottom && "margin-bottom: " + props.marginBottom + "px;"};
    `; 
  }}
`;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank u very much! that makes my life so much easier and prettier :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.