divcomponents
- Text components
- Pass in as a prop to style components
- Set equal to an object containing CSS properties
<View style={styles.container}>
...
</View>const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});- Container styles will not be inherited
- ex. body container has font weight bold, text inside container are unaffected
- however, nested
Textcomponents will inherit parent styles
<TextInput
placeholder='name'
onChangeText = {(val) => {setName(val)}}
multiline
keyboardType='numeric'
></TextInput>placeholderis the default text in input fieldonChangeTextfires on input change and automatically takes in the value in the text field -valin this casemultilineexpands the text field on enter keypresskeyboardTypechanges keyboard input type
<ScrollView>
{people.map((person, index) => (
<View key={index}>
<Text style={styles.item}>{person.name}</Text>
</View>
)
)}
</ScrollView>- Output a list
- The list is very long so we need to wrap it with the
ScrollViewcomponent in order to scroll down
<FlatList
keyExtractor={(item) => item.id}
data={people}
renderItem={({ item }) => (
//jsx
<Text style={styles.item}>{item.name}</Text>
)}
/>dataspecifies output datarenderItemis a function that returns JSX- Takes in a destructured item which represents the value in the array item we are outputting
- No key required: automatically checks for a
keyproperty in the object keyExtractorlets you choose which property will be used as the key (in this case we use theidproperty)- All items are not immediately rendered, more load as you scroll down
- Best for lists of data
<TouchableOpacity onPress={() => pressHandler(item.id)}>
<Text style={styles.item}>{item.name}</Text>
</TouchableOpacity>- Turn any component into a button and perform actions with
onPress
Alert.alert('Title', 'body', [
{text: 'button', onPress: () => console.log('alert closed')}
]);- Shows an alert popup
- Close the keyboard on touch the app body
- Wrap the entire container with a touchable component
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View>
main container view
</View>
</TouchableWithoutFeedback>keyboard.dismiss()dismisses the keyboard
Viewcomponents use flexbox under the hood
flex: 1 - the "growth" rate, how much space the items take up
- Everything inside the flex container is now a flex item, taking up all available width
const [fontsLoaded, setFontsLoaded] = useState(false);
if(fontsLoaded) {
return (
<Home />
)
} else {
return (
<AppLoading
startAsync={getFonts}
onFinish={() => setFontsLoaded(true)}
)
}- A smart way to deal with asynchronous code using the
useStatehook - In this example, we are waiting for fonts to load through
getFonts - Until the fonts are loaded, we use the Expo
AppLoadingcomponent whichonFinishloads the desiredHomecomponent
- Create styles in modules
// styles/global.js
import { StyleSheet } from 'react-native';
export const globalStyles = StyleSheet.create({
// styles here
})import { globalStyles } from '...'- Push/pop screens on a stack
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack';
// ... imports for Home, About
const Stack = createStackNavigator();
export const Routes = () => {
return (
<NavigationContainer>
<Stack.Navigator>
// renders home by default - on top of stack
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="About" component={About} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default Routes;- Every screen we configure automatically gets a navigation prop
const { navigation } = props;
navigation.navigate('Home');
navigation.push('Home');
navigation.goBack();- In this example, we want to navigate to whatever component
Homehas as its screen
- Always pushes the route on top of the stack
- Will pop back to earlier in the stack if a component is already mounted there
- Pops screen of the stack
navigation.navigate('Home', {name: 'danny', cool: true})- Can send parameters of data as a second parameter
// component takes in { route } as a prop
const { name, cool } = route.params;
<Text>{ navigation.getParam('name')}</Text>- Pass in the key that you want to access from the passed in parameters
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="About" component={AboutScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}export default function Card(props) {
return (
<View style={styles.card}>
<View style={styles.cardContent}>
{ props.children }
</View>
</View>
)
}<Card>
<Text>hello</Text>
<Text>hey there</Text>
</Card>props.childrenare similar to slots in Vue- It passes in the nested elements into the Native component
<Image source={require('url')} />
<Image source={image} /> - image variable
<ImageBackground source={require('url')}>
Wrapped Components
</ImageBackground>- Pop up windows
<Modal visible={modalOpen} animationType='slide'>
<Button onPress={() => setModalOpen(false)} />
Wrapped Components
</Modal>- Visibility is bound to
modalOpenstate boolean- Combined with the
useStatehook, we can usesetModalOpento open/close the modal
- Combined with the
- Animation is set to
slide
import { Formik } from 'formik';
<Formik
initialValues={{ title: '', body: '' }}
onSubmit={(values, actions) => {
actions.resetForm();
function(values);
}}
>
{(formikProps) => (
<View>
<TextInput
placeholder="Title"
onChangeText={formikProps.handleChange('title')}
value={formikProps.values.title}
/>
<Button title="Submit"onPress={formikProps.handleSubmit} />
</View>
)}
</Formik>- The
valuesparameter represents the values in the form fields as an object - Inside the
<Formik>tags we create the form fields inside arenderfunction returning JSX formikPropsinclude helpful functions provided by Formik.handleChange()takes in the value we want to change- In the
valuesprop foronSubmit, we update
- In the
- The
valueof the<TextInput>is alsovalues.title(2 way binding) formikProps.handleSubmitruns theonSubmitfunction for usactions.resetForm()resets fields