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
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}) => {}
This:
Is equivalent to:
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:
You can do:
And you don’t have to retype the prop names over again.