In this React Native lesson we are going to learn about React Native Props, so Props are short for properties and it is used to pass some value from one component to another component, or we can say using props we can feed some value from the parent component to the child component, you can use props in functional component and also class component, but remember that react props are immutable, it means that you can not change the value of the props once it is assigned.
First we are going to use functional component, this is my App.js and you can see that i have passed some value to my child component that is Hello.js.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import Hello from './components/Hello'; export default function App() { return ( <View> <Hello name = "Parwiz" lastname = "Forogh"/> </View> ); } |
Now we can access to this value in our Hello.js component using props, you need to pass props in your functional component as parameter and after that you can access to the values using that props.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import React from 'react'; import {View, Text, StyleSheet} from 'react-native'; const Hello = (props) => { return( <View> <Text style = {styles.textStyle}> {`My name is ${props.name} My lastname is ${props.lastname}`} </Text> </View> ) } const styles = StyleSheet.create({ textStyle: { fontSize:30, color:"red", padding:50 } }) export default Hello; |
First run this command
1 |
npm start |
This will be the result.
Props in Class Component
Also we can use props in class component, so this is my App.js file, and we have added a value to our child component, now we can access to this value in our class component using props.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import Hello from './components/Hello'; import HelloClass from './components/HelloClass'; export default function App() { return ( <View> {/* <Hello name = "Parwiz" lastname = "Forogh"/> */} <HelloClass website = "geekscoders.com"/> </View> ); } |
This is our HelloClass.js file, now in a class component we don’t need to pass props as parameter, it is built in with our class and you can use this keyword to access to the props.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import React, {Component} from 'react'; import {View, Text, StyleSheet} from 'react-native'; class HelloClass extends Component { render(){ return( <View> <Text style = {styles.textStyle}>{`My website is ${this.props.website}`}</Text> </View> ) } } const styles = StyleSheet.create({ textStyle: { fontSize:30, color:"brown", padding:20 } }) export default HelloClass; |
Run your application and this is the result.