Reputation: 1499
I recently learned how to pass different styles based on component and was hoping the same rule applied for passing different props but I'm having a hard time with it.
So here I have a text component:
const TextTitle = ({ text }) => (
<Text
accessible={true}
style={styles.songTitleText}
numberOfLines={2}
ellipsizeMode={'tail'}
>
{text}
</Text>
);
but I want to use this text component elsewhere but instead, only give it numberOfLines={1}
So I tried
const SongTitle = ({ text, numberOfLines }) => (
<Text
accessible={true}
style={styles.songTitleText}
numberOfLines={[2, numberOfLines]}
ellipsizeMode={'tail'}
>
{text}
</Text>
);
and then in another component I call it with:
<TextTitle
style={styles.itemText}
text={Text_Word}
numberOfLines={1}
/>
But I get an error in my simulator: JSON Value '(2, 1)' of type NSMutableArray cannot be converted to NSNumber
Any suggestions?
Thanks!
Upvotes: 0
Views: 509
Reputation: 57964
You cannot do this the same way you do with styles. I'm guessing you want to have the numbers of lines default to two, but when the user explicitly passes it, to use that value. If so, you can use the logical OR operator:
const TextTitle = ({ text, numberOfLines }) => (
<Text
…
numberOfLines={numberOfLines || 2}
>
…
</Text>
);
This checks to see if numberOfLines
was passed to the component. If yes, then it's used, if not, the default of 2 is used. This is because the logical OR operator evaluates to the left operand if it's truthy, and the right operand if it is falsey.
Note that there's also a more readable built-in way of accomplishing this with logical OR, assigning the defaultProps
static property. Per the documentation:
You can define default values for your props by assigning to the special defaultProps property
Thus:
const TextTitle = ({ text, numberOfLines }) => (
<Text
…
numberOfLines={numberOfLines}
>
…
</Text>
);
TextTitle.defaultProps = {
numberOfLines: 2
};
This does the same thing as above, just more readable and "semantically correct" as React offers this for you as a built-in feature.
Upvotes: 1