View and Text
Every screen in Sprout, however fancy, is built mostly from two components. View arranges things and Text says things. They look like div and span, but each has habits of its own that trip up web developers.
The rule
View arranges and holds; Text shows words and nests other Text.
View is the basic building block of layout. It can hold any components, take a style, respond to layout and accessibility props, and it uses Flexbox by default. A View never shows text itself.
<View style={{ padding: 16, backgroundColor: '#eef7ee' }}>
<Text style={{ fontSize: 20, fontWeight: 'bold' }}>Fern</Text>
<Text>
Next water: <Text style={{ fontWeight: 'bold' }}>tomorrow</Text>
</Text>
</View>Text has three habits worth learning:
- Nesting. A
Textinside aTextflows inline, like aspan, and inherits the outer text's styles such as colour and font size. That is how "tomorrow" becomes bold mid-sentence above. - No inheritance from
View. Acoloron aViewdoes nothing for theTextinside it. Text styles only pass fromTextto nestedText. - Truncation.
numberOfLines={1}cuts long text with an ellipsis, handy for long plant notes.
Text also supports onPress, so a word can be tappable, and selectable to let users copy it.
Two more web habits do not carry over. A View never scrolls when its content is too tall; the extra content is simply cut off until you use a scrolling component. And text cannot be selected and copied unless you add selectable.
The shortcut
Before writing a screen, sketch it as boxes and words: every rectangle is a View, every run of words is a Text, and any styled word inside a sentence is a nested Text.
The card
One rectangle with padding and a background. That is a
View.
The trap is putting color: 'green' on the card View and wondering why the text stays black. Move it to the Text.
Drills
Answer fast — trust the rule.
You set color: 'green' on a View. What colour is the Text inside it?
How do you make one word bold in the middle of a sentence?
Which prop shows at most one line of a long note, ending with an ellipsis?
A nested Text sits inside an outer Text with fontSize: 18. What font size does the inner one use if it sets none?
Remember
Viewarranges and holds;Textshows words and nests otherText.- Sketch as boxes and words: rectangles are
View, words areText. - Trap: text styles on a
Viewdo not reach theTextinside.
