skip to Main Content

Hi I’m learning React and Typescript and I have a question regarding the meaning of syntax.

Suppose I have a code snippet of test.tsx below.

// prop is defined somewhere over here.
...

private displayMyList = (props: Props) => {
   return <MyList name_prop={this.props.name} {...props}> </MyList>;
};

<MyList name_prop={this.props.name} means passing this.props.name value to name_prop of MyList component
so that MyList component can use this.props.name via name_prop

But what does {...props} inside of right-angle bracket > do?

If it’s outside of right-angle bracket like

return <MyList name_prop={this.props.name}> {...props} </MyList>; 

then it simply displays {...props}.

However, if {...props} is inside of >,

return <MyList name_prop={this.props.name} {...props}> </MyList>; 

the
what does this syntax mean?

2

Answers


  1. it means "the other/rest" of props. Instead of naming each of your props, you can just propagate them down and then you can extract what you need.
    Take a look: Forwarding props. With your example you can use: <MyList {...props}> </MyList> and then: const MyList = ({name_prop}) => {}

    Login or Signup to reply.
  2. This:

    const props = { a: 123 }
    <Foo {...props} />
    

    Is equivalent to:

    <Foo a={123} />
    

    So it applies an object as if the properties of that object were used as component props.

    It this case, it’s used as a way to forward props to an inner component.

    So instead of:

    function FooWrapper({ a, b }: Props) {
      return <Foo a={a} b={b} />
    }
    

    You can do:

    function FooWrapper(props: Props) {
      return <Foo {...props} />
    }
    

    And you don’t have to retype the prop names over again.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search