âpropsâ and âstateâ are two important concepts in React Native. Using React Native Props and State, we can control one component. In this tutorial, we will learn how to use âpropsâ and âstateâ with examples.
Props
In React Native, each reusable element can be created as a component. For example, if you have a feed list with one image and title, we can create one component for that element and use that element on each row of the feed. Each row will use the same component with different image and title.
Again, in our application, if that same view with image and title is required on any other page, we can simply use that component.
But how are we going to pass the values that the component will load? In this example, we need to pass a different image URL and title for each row to the same component. âpropsâ is used for that. If you are familiar with ReactJs, the concept of props is the same. We can assign different âpropsâ to different component instance and each instance will use the value of âpropsâ to render its views.
âpropsâ stands for âpropertiesâ. Normally, a parent component passes prop to its child components. The child component uses the values defined in the props. Using props, it becomes easy to write reusable code.
Using props in components:
In most system components, we need to use props because these components will look differently for different properties. For example, to add one image in a react-native application, the following âImageâ component is required :
xImage source={url} style={{width: 100, height: 100}}/x
Here, âsourceâ is a props. We can pass different url and it will show different images. Note that we are using the same component âImageâ but the props âurlâ is different.
One thing we should remember that âpropsâ are immutable, i.e. we canât change them. Also, props are passed from parent to its child, i.e. in top-down manner.
Create a custom component :
Letâs create one custom component that accepts a âpropsâ. We will create one simple component and show it differently using different props values.
First of all, create one simple react-native project. Create one file âCustomCard.jsâ on the root folder and add the below code :
import React, {Component} from 'react'; import { Image, View, Text, } from 'react-native'; class CustomCard extends Component { render() { return ( xViewx xText x{this.props.title}x/Textx xImage source={this.props.url} style = {{width: 300, height : 250}}/x x/Viewx ); } } export default CustomCard;
This is a react component. We can import it and load it like any other view components. When this component will load, it will execute the render() method, that returns one view that will be returned from wherever it was used.
Inside the return View, we have one Text and one Image. The text is showing the value of âtitleâ that it receives from âpropsâ. Similarly, the Image loads one image using the âurlâ that it receives from the same âpropsâ.
Now, open the âApp.jsâ file and change its content as like below :
import React, {Fragment} from 'react'; import CustomCard from './CustomCard'; const App = () =x { let firstImage = { uri: 'https://upload.wikimedia.org/wikipedia/commons/e/ec/Cones500.jpg'}; let secondImage = { uri: 'https://upload.wikimedia.org/wikipedia/commons/4/40/Amsterdam_(NL),_Spui_--_2015_--_7227.jpg'}; return ( xFragmentx xCustomCard url={firstImage} title={"First title"}/x xCustomCard url={secondImage} title={"Second title"}/x x/Fragmentx ); }; export default App;
Here, âfirstImageâ and âsecondImageâ are two different urls of two different images. It is the root component i.e. the App will load the content that is returned from this componentâs render method.
Inside ârenderâ, we are using âCustomCardâ components two times. Each time we are passing two values : âurlâ and âtitleâ. These values are used in the component as âthis.props.urlâ and âthis.props.titleâ respectively. Run the app and it will give one output like below :
As you can see here, the same component was loaded with different image and text.
State :
Previously I have mentioned that âpropsâ are set by the parent component and they are passed to a child component. The child component canât change the values in âpropsâ. For handling any changeable data we need to use a different component property called âstateâ.
A âstateâ is used to store data that may change in a component. Each component has a different âstateâ values. Based on these values, the UI is changed.
One more important thing is that we canât change any value in a state directly. For that, we need to call one method called âsetStateâ. This method modifies the current state and re-render the whole component.
We are using the same example explained above. Change the CustomCard.js file as like below :
import React, {Component} from 'react'; import { Image, View, Button, Text, } from 'react-native'; class CustomCard extends Component { constructor(props){ super(props) this.state = {isHidden : false} } showHideText = () =x { this.setState({isHidden : !this.state.isHidden}) } render() { return ( xViewx {!this.state.isHidden xx xText x{this.props.title}x/Textx} xImage source={this.props.url} style = {{width: 300, height : 250}}/x xButton title="Click Me" onPress={this.showHideText}/x x/Viewx ); } } export default CustomCard;
Output
If you run the program now, it will look as like below :
We have added one button at the bottom of the component. If you click any one of these buttons, it will hide and show the title text on each click.
Look at the code closely. The âconstructorâ method is called whenever the component is created, i.e. before ârenderâ is called. Inside the âconstructorâ, we are initializing the âstateâ. It has only one boolean value âisHiddenâ and its initial value is âfalseâ.
In the âreturnâ statement of the ârenderâ method, the âTextâ component will be shown only if the value of âisHiddenâ defined in the âstateâ is âfalseâ. Else, it will be hidden. For checking the current value in a âstateâ, we are using âthis.stateâ.
In the âButtonâ component, if we click on it, it will execute the method pointed by the âonPressâ props i.e. the arrow function âshowHideTextâ. Each time you click on the button, it will call the same method. Inside this method, we are changing the current value of âisHiddenâ defined in âstateâ.
this.setState({isHidden : !this.state.isHidden})
We are changing it to â!this.state.isHiddenâ i.e. if the value is âtrueâ, it will be âfalseâ and if it is âfalseâ, it will be âtrueâ. For changing anything inside a âstateâ, âthis.setStateâ method is called. Once we call this method, the component will re-render again. So, if the value of âisHiddenâ becomes âtrueâ, the âTextâ will be hidden and if it becomes âfalseâ , âTextâ will be shown.
We canât change any value in a state directly. The âsetStateâ method is required to change it. We can change one or more state values using this method. Also, the state is different on each component object.
Difference between React Native Props and State:
Following are the main difference between state and props in react-native :
- Props are immutable but state is mutable.
- Props are normally passed from parent component to its child component. But, state is maintained in each component.
- Using props, we can change the state of a parent component.
Conclusion
This concludes the details you require on React Native Props and State. The article tells you how you can use them to build robust and maintainable Native Applications.
Tutorial Index
- Tutorial #1 â React Native â Introduction
- Tutorial #2 â React Native Props and State
- Tutorial #3 â Styling React Native App
- Tutorial #4 â React Native UI Components
- Tutorial #5 â React Native API Integration
- Tutorial #6 â React Native Animation
- Tutorial #7 â Top 10 React Native libraries