Components and JSX in React Native
You already know JSX from React for the web. In Sprout, the first thing that breaks is habit: you type <div> and <p>, and the app shows a red error. The syntax is the same; the vocabulary is different.
The rule
Same JSX, new words: View for boxes, Text for every string.
A component is a function that returns JSX. In React Native the JSX uses components imported from react-native instead of HTML tags:
import { View, Text } from 'react-native';
function PlantCard() {
return (
<View>
<Text>Fern</Text>
<Text>Water every 3 days</Text>
</View>
);
}The two you use most:
Viewis a container, like adiv. It holds other components and is used for layout.Textdisplays text. It is the only place a string can appear.
That second rule is strict. This fails with the error "Text strings must be rendered within a <Text> component":
<View>Fern</View>Everything else about JSX is the same as on the web: one parent element (or a fragment <>...</>), curly braces {} for JavaScript expressions, and component names start with a capital letter. There is no className: styles are passed with the style prop instead.
Components nest. App can render several PlantCards, each built from View and Text. This tree is what React Native turns into native views.
Every built-in component must be imported before use. Forget Text in the import line and the app stops with an error saying Text is not defined. Your own components, like PlantCard, usually live in their own files and are imported the same way.