Brian
Brian

Reputation: 528

Do you need to add ...restProps for compound components in react?

I'm following a course and for the footer, they added ...restProps for every element. I don't understand why you need to do that if you're simply just creating a footer with no properties.

Here is the code

      export default function Footer({ children, ...restProps }) {
        return <Container {...restProps}>{children}</Container>;
      }

      Footer.Row = function FooterRow({ children, ...restProps }) {
        return <Row {...restProps}>{children}</Row>;
      };

      Footer.Column = function FooterColumn({ children, ...restProps }) {
        return <Column {...restProps}>{children}</Column>;
      };

      Footer.Link = function FooterLink({ children, ...restProps }) {
        return <Link {...restProps}>{children}</Link>;
      };

      Footer.Title = function FooterTitle({ children, ...restProps }) {
        return <Title {...restProps}>{children}</Title>;
      };

Here is where it is actually implemented

           <Footer>
            <Footer.Title>Questions? Contact us.</Footer.Title>
            <Footer.Break />
            <Footer.Row>
              <Footer.Column>
                <Footer.Link href="#">Home</Footer.Link>
                <Footer.Link href="#">About Us</Footer.Link>
                <Footer.Link href="#">Contact Us</Footer.Link>
                <Footer.Link href="#">Support</Footer.Link>
              </Footer.Column>

so far I understand why you add children because you need your footer menus text to show up, but I don't get why you need to add ...restProps to every footer element when only the links have something that you can customize.

Am I missing something, or is it not necessary to do this? Is this a proper way for creating a footer with compound components?

Upvotes: 2

Views: 2588

Answers (1)

SrThompson
SrThompson

Reputation: 5748

TL;DR: You don't NEED to pass those props down, but you SHOULD.

Long answer:

You pass restProps to the returned component because that way you can define the props of the internal component from outside via the parent component. Let's say your Container component has a width prop. Defining your Footer without passing restProps you won't be able to set the width prop (or default props like style). So this:

<Footer width={100} />

Works if you use ...restProps, and sets the width of the Container to 100, but it doesn't do anything if you don't.

Upvotes: 4

Related Questions