React Native set View Align Horizontally Center dynamically on button click

The Style attribute alignItems : ‘ ‘ is used on a View or component to set their children alignment. There are 4 different options available in this attribute flex-start, center, flex-end, and stretch. So in this tutorial we would going to set View Align Horizontally Center dynamically on button click using alignItems :’center’ in react native android iOS app example. We would set this value on application run time, So when app user click on the button then it will update the State value and according to that value we would set the align center. So let’s get started .

Content in this project set View Align Horizontally Center dynamically on button click in react native android iOS app example:

1. Import StyleSheet, View and Button component in your project.

2. Create a State named as Align in constructor() and set its default value as False.

3. Create a function named as Set_Align_Horizontal_Center_Method(). This function would update the Align State value to True.

4. Create a Root View in renders’s return block. We would call call the Custom CSS style class in this View . Now using the Style Array Method we would call another Style attribute alignItems. We would use the Ternary operator with state value. So when the State value is false it will by default set the alignItems: ‘flex-start’ and on button click when the state value is updated as True then it will set the alignItems: ‘center’ . After updating the State value all of its children view will be aligned in Horizontally center.

5. Create a Child View and Button in Root View. We would call the Set_Align_Horizontal_Center_Method() function on button onPress event.

6. Create Style.

7. Complete source code for App.js File :

Screenshot in Android :


set View Align Horizontally Center dynamically

 

Screenshot in iOS device :