Reputation: 934
I am trying to call one subcomponent within the same class but it throws an error If I use it with curly braces it's working fine.
Below code throws an error:
public TotalCostSavings = () => {
return <View />;
};
public Savings = () => {
return (
<View>
<this.TotalCostSavings />
</View>
);
};
Error: `
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports`
The below code works fine:
public TotalCostSavings = () => {
return <View />;
};
public Savings = () => {
return (
<View>
{this.TotalCostSavings()}
</View>
);
};
Why the first approach is not working?
Upvotes: 0
Views: 29
Reputation: 42228
The issue here is just the naming. React expects that all components start with an uppercase name. If it sees a lowercase name then it assumes it's a built-in DOM element like a div
. You have a problem because this
is lowercase, which obviously you cannot change.
This works just fine because the JSX element now has an uppercase name Aliased
:
public Savings = () => {
const Aliased = this.TotalCostSavings;
return (
<View>
<Aliased />
</View>
);
};
It would make more sense to define them as functions and call them that way:
renderTotalCostSavings = () => {
return <View />;
};
renderSavings = () => {
return (
<View>
{this.renderTotalCostSavings()}
</View>
);
};
Upvotes: 0