I am using material ui tab panel in react. I want to pass the component created by container to the component property of the tab panel. But I'm stuck with infinite rendering... I'm looking for a reason. While looking at someone else's code, I found out that the part different from mine was in return. I wonder what the difference is.
//SupportCenterContainer.js
function RequestNotice(props) {
return <Containers.SupportNoticeListContainer />;
}
function RequestNotice2(props) {
return () => <Containers.SupportNoticeListContainer />;
}
function RequestNotice3(props) {
return () => {
return <Containers.SupportNoticeListContainer />;
};
}
CodePudding user response:
In the first function, you are returning the component itself, which is the normal behavior that you expect from a return in a function.
In the second case, you are returning an anonymous function, that when called will return the component itself. This happens because when you use arrow functions and immediately has something typed after the arrow, these value will be the return of that function.
In the third case, you are using the same idea of the anonymous function with the arrow notation, but since you have a curly brace before the value, you must specify what will be returned by that function.
Just for curiosity, the arrow function was introduced do JS in ES6.
CodePudding user response:
function RequestNotice3(props) {
return () => {
return <Containers.SupportNoticeListContainer />;
};
}
function RequestNotice2(props) {
return () => <Containers.SupportNoticeListContainer />;
}
The above code is returning a function which in turn will return a React component.
To use this, you can do
let Component = RequestNotice2(props)() // <Containers.SupportNoticeListContainer />
// render the component
<Component/>
CodePudding user response:
In short, in ES6, () => value
means it returns the value
.
However, if you open a {
after the parenthesis, the value must be returned using return value
e.g () => { return value }
.
The use case for the latter is when you have to do some logic to derive the value:
() => { value = 5 8; return value }
So the comments above each explains each scenario:
// Returns the <Containers.SupportNoticeListContainer /> component
function RequestNotice(props) {
return <Containers.SupportNoticeListContainer />;
}
// Returns a function that will return <Containers.SupportNoticeListContainer /> when called
function RequestNotice2(props) {
return () => <Containers.SupportNoticeListContainer />;
}
// same as above, will return <Containers.SupportNoticeListContainer /> when called
function RequestNotice3(props) {
return () => {
return <Containers.SupportNoticeListContainer />;
};
}