I am struggling to get this.setState to work with react-native. I keep getting this.setState is not a function error. I am using an arrow function, which i thought would use the enclosing scope and there was no need to bind to this. But it is not working as expected. I appreciate any help i can get.
**
* Sample React Native App
* https://github.com/facebook/react-native
*
* #format
* #flow strict-local
*/
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Button,
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
const App: () => React$Node = () => {
state = {
textValue: 'Original Text'
};
buttonPress = () => this.setState({textValue: 'New Text'})
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<Header />
{global.HermesInternal == null ? null : (
<View style={styles.engine}>
<Text style={styles.footer}>Engine: Hermes</Text>
</View>
)}
<View style={styles.body}>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>{this.state.textValue}</Text>
<Button
onPress={buttonPress}
title="Learn More"
color="#841584"
accessibilityLabel="This is a button"
/>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Step One</Text>
<Text style={styles.sectionDescription}>
Edit <Text style={styles.highlight}>App.js</Text> to change this
screen and then come back to see your edits.
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>See Your Changes</Text>
<Text style={styles.sectionDescription}>
<ReloadInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Debug</Text>
<Text style={styles.sectionDescription}>
<DebugInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Learn More</Text>
<Text style={styles.sectionDescription}>
Read the docs to discover what to do next:
</Text>
</View>
<LearnMoreLinks />
</View>
</ScrollView>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;
Use react hooks
import React, { useState } from 'react'
const App: () => React$Node = () => {
const [textValue, setTextValue] = useState('Original Text')
buttonPress = () => setTextValue('New Text')
...
}
If you want to use the setState feature, class definition is required. Like this.
class App extends React.Component {
constructer(props) {
super(props)
this.state = {
textValue: 'Original Text'
};
}
buttonPress = () => this.setState({textValue: 'New Text'})
render () {
return (
...
)
}
}
If you want to use the function, please read the document.
https://reactjs.org/docs/hooks-intro.html
Related
Version:
"react-native": "0.68.2",
"react-native-paper": "5.0.0-rc.3",
"react-native-vector-icons": "^9.2.0",
Problem: the fontFamily in the
<Text variant="displayLarge" theme={{ typescale: { displayLarge: { fontSize: 30, fontFamily: 'HelveticaNeue-Thin' },},}}> does not take effect while the <Text style={theme.fonts.thin}> does works as expected.
https://snack.expo.dev/#wztrustgrid/fontfamilyintheme
import { StyleSheet, View } from 'react-native';
import {
configureFonts,
Provider as PaperProvider,
MD3LightTheme as DefaultTheme,
Text,
} from 'react-native-paper';
const fontConfig = {
ios: {
thin: {
fontFamily: 'HelveticaNeue-Thin',
fontSize: 30,
},
},
};
const theme = {
...DefaultTheme,
fonts: configureFonts(fontConfig),
};
export default function App() {
return (
<PaperProvider
theme={theme}
>
<View style={styles.container}>
{/* Display correct font */}
<Text style={theme.fonts.thin}>
ABCDEFGHIJKLM NOPQRSTUVWXYZ abcdefghijklm nopqrstuvwxyz 1234567890
</Text>
{/* Display incorrect font */}
<Text
variant="displayLarge"
theme={{
typescale: {
displayLarge: { fontSize: 30, fontFamily: 'HelveticaNeue-Thin' },
},
}}
>
ABCDEFGHIJKLM NOPQRSTUVWXYZ abcdefghijklm nopqrstuvwxyz 1234567890
</Text>
</View>
</PaperProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
**how to pass array of multiple object in database react native . i aslo tried axios fetch and redux but its not responding **
import React, { useState, useEffect, useLayoutEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TouchableOpacity, ScrollView, Dimensions } from 'react-native';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import _ from "lodash"
import ClassSectionFilter from '../singleStudentAttendance/ClassSectionFilter';
import { CheckBox } from 'react-native-elements';
import { useIsFocused } from "#react-navigation/native";
import { useRegisterTechAttendanceMutation } from '../../../services/userAuthApi';
import Toast from "react-native-toast-message";
import axios from 'axios'
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const MarkAttendanceScreen = ({ navigation, route }) => {
const [columns, setColumns] = useState([
"RollNo",
"Name",
])
const [direction, setDirection] = useState('')
const [selectedColumn, setSelectedColumn] = useState('')
const [ teachers , setTeachers] = useState([]);
const [ attendance, setAttendance ] = useState()
const [ attendanceState, setAttendanceState ] = useState('')
const fetchData = async () => {
const resp = await fetch(`http://192.168.18.64:8000/api/user/getSometeacher/${route.params.schoolId}`);
const data = await resp.json();
const schAdminId = (data.map(l => l._id ? { ...l, schoolAdminID: route.params.schoolAdminID } : l));
setAttendanceState(schAdminId)
};
const focus = useIsFocused();
useLayoutEffect(()=>{
fetchData();
}, [focus])
const MarkAttendance = (item, S) => {
const attend = (attendanceState.map(l => l._id === item._id ? { ...l, attendance: S } : l));
setAttendanceState(attend)
setAttendance(attend)
}
const [items, setItems] = useState()
const sortTable = (column) => {
const newDirection = direction === "desc" ? "asc" : "desc"
const sortedData = _.orderBy(teachers, [column], [newDirection])
setSelectedColumn(column)
setDirection(newDirection)
setTeachers(sortedData)
}
const [registerTechAttendance] = useRegisterTechAttendanceMutation();
const handleFormSubmit = async () => {
const bodyFormData = new FormData();
attendance.forEach((item) => {
bodyFormData.append('attendance', item);
});
const res = axios.post('http://192.168.18.64:8000/api/user/teacherattendance', bodyFormData)
if (res.data.status === "success") {
navigation.navigate("SchoolAdminHomePage");
}
if (res.data.status === "failed") {
Toast.show({
type: "warning",
position: "top",
topOffset: 0,
text1: res.data.message,
});
}
};
// const onSubmit = () => {
// const formData = new FormData()
// formData.append(attendance);
// console.log(formData)
// fetch('http://192.168.18.64:8000/api/user/teacherattendance', {
// method: "POST",
// body: JSON.stringify(formData),
// headers: {
// 'content-type': 'application/json',
// }
// })
// .then((response) => console.log(response))
// .catch(err => {
// console.log(err);
// })
// }
const tableHeader = () => (
<View style={styles.tableHeader} >
{
columns.map((column, index) => {
{
return (
<TouchableOpacity
key={index}
style={styles.columnHeader}
onPress={() => sortTable(column)}>
<Text style={styles.columnHeaderTxt}>{column + ""}
{selectedColumn === column && <MaterialCommunityIcons
name={direction === "desc" ? "arrow-down-drop-circle" : "arrow-up-drop-circle"}
/>
}
</Text>
</TouchableOpacity>
)
}
})
}
</View>
)
return (
<View style={{ height: windowHeight, width: '100%' }}>
<View >
<ClassSectionFilter />
</View>
<FlatList
data={attendanceState}
keyExtractor={(item, index) => index + ""}
style={{ maxWidth: '100%' }}
ListHeaderComponent={tableHeader}
stickyHeaderIndices={[0]}
extraData={attendanceState}
renderItem={({ item, index }) => {
return (
<View style={{ ...styles.tableRow, backgroundColor: index % 2 == 1 ? "#F0FBFC" : "white", width: '100%', }}>
<Text style={{ ...styles.columnRowTxt, fontWeight: "bold" }}>{item.roll_no}</Text>
<Text style={{ ...styles.columnRowTxt }}>{item.first_name}</Text>
<ScrollView horizontal={true}
showsHorizontalScrollIndicator={true}
pagingEnabled={true}
style={{ width: '150%' }}
>
<View style={{ flexDirection: 'row', left: 40 }}>
<View
style={{
left: 23
}}
>
<CheckBox
title='P'
checkedColor='green'
checked={item.attendance === 'P' ? true : false}
checkedIcon="dot-circle-o"
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'P')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 50,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent'
}}
/>
{/* <BouncyCheckbox
size={20}
fillColor="green"
unfillColor="#FFFFFF"
text="P"
iconStyle={{ }}
textStyle={{ }}
onPress={()=>MarkPresent()}
isChecked={false}
/> */}
</View>
<View style={{
left: 5
}}>
<CheckBox
title='A'
checkedColor='red'
checked={item.attendance === 'A' ? true : false}
checkedIcon="dot-circle-o"
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'A')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 50,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent'
}}
/>
{/* <BouncyCheckbox
size={20}
fillColor="red"
unfillColor="#FFFFFF"
text="A"
iconStyle={{ }}
textStyle={{ }}
onPress={()=>MarkAbsent()}
/> */}
</View>
<View style={{
left: 5,
}}>
<CheckBox
title='L'
checkedColor='gray'
checked={item.attendance === 'L' ? true : false}
checkedIcon='dot-circle-o'
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'L')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 70,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent',
}}
/>
</View>
</View>
</ScrollView>
</View>
)
}}
/>
<View>
<TouchableOpacity
onPress={handleFormSubmit}
style={{
justifyContent: "center",
alignItems: "center",
padding: 15,
width: "100%",
marginVertical: 5,
borderRadius: 50,
marginBottom: 60,
fontWeight: "bold",
backgroundColor: "#5062BD",
elevation: 1,
marginTop: 30,
bottom:20,
}}
>
<Text
style={{
color: "white",
justifyContent: "center",
alignItems: "center",
}}
>
Submit Attendance
</Text>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
tableHeader: {
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
backgroundColor: "#5062BD",
borderTopEndRadius: 10,
borderTopStartRadius: 10,
height: 50,
},
tableRow: {
flexDirection: "row",
height: 40,
margin: 2,
left: 8
},
columnHeader: {
width: "16%",
justifyContent: "center",
alignItems: "flex-start",
margin: 10
},
columnHeaderTxt: {
color: "white",
fontWeight: "bold",
},
columnRowTxt: {
width: "18%",
}
});
export default MarkAttendanceScreen
data also show in my console but it is not posting. i am also trying redux, fetch and axios method but its not give me a solution
enter image description here
Hello everyone i am learning REACT-NATIVE from last two months , i got a small issue with if-else condition render method ,while i am executing the code if condition is not working properly .
Can you please tell me the solution
import React, { Component } from 'react';
import {
Image, Platform, StyleSheet, Text, View, TextInput, Button, TouchableHighlight, Alert,
TouchableOpacity, ScrollView, ColorPropType, FlatList, SectionList, Dimensions, AsyncStorage,
Keyboard,
} from 'react-native';
import axios from 'axios';
import GlobalStore from '../GlobalStore';
const API_URL = GlobalStore.BASE_URL;
var ACCESS_TOKEN = 'access_token';
export default class LogInScreen extends React.Component {
static navigationOptions = {
title: 'LogIn',
headerStyle: {
backgroundColor: '#03A9F4',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
};
/* *********** Code Starts Here ****************** */
constructor(props) {
super(props);
this.state = {
error: '',
userId: '',
user_id: '',
mobile: '',
password: '',
Token: '',
};
}
componentDidMount() {
this.get_Id();
this.getToken();
}
// get id from asyncStorage
async get_Id() {
try {
const userId = await AsyncStorage.getItem('USER_ID') // (STORAGE_KEY)
if (userId !== '' || userId !== null) {
this.setState({ userId: userId })
console.log('profile get_id id: =>', userId)
// this.getUserDetails(userId)
} else {
console.log('profile get_id id: => user_id=null')
Alert.alert('No user profile found LogIn Now ' + this.props.navigation.navigate('LogIn'))
}
} catch (error) {
alert('Failed to load profile get_Id() user_id.')
}
}
async storeToken(accessToken) {
try {
await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
this.getToken();
} catch (error) {
console.log('LogIn AsyncStorage Error: ' + error.message);
}
}
async getToken() {
try {
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
this.setState({ Token: token })
console.log("LogIn Get token is :" + token);
} catch (error) {
console.log("something went wrong in getToken LogIn page")
}
}
async removeToken() {
try {
await AsyncStorage.removeItem(ACCESS_TOKEN);
this.getToken();
} catch (error) {
console.log("some thing went wrong removeToken LogIn page")
}
}
validate_Fields = () => {
const { mobile, password } = this.state
if (mobile == "") {
Alert.alert("please enter Mobile Number");
return false
}
if (mobile.length < 10) {
Alert.alert("please enter 10 digit Mobile Number");
return false
}
if ((password === "" && password.length < 6)) {
Alert.alert("please enter password minimum length should be 6");
return false
}
return true
}
// logIn function
logInUser() {
if (this.validate_Fields()) {
const { mobile, password } = this.state;
this.setState({ error: '', loading: true });
// NOTE HTTP is insecure, only post to HTTPS in production apps
axios.post(API_URL + '/usersapi/user_LogIn', {
mobile_no: mobile,
password: password
})
.then((response) => {
// console.log(JSON.stringify(response));
let accessToken = response.data.TOKEN;
this.storeToken(accessToken);
console.log("dataToken-LogIn:" + accessToken);
Alert.alert('LogIn Successfully ' + this.props.navigation.navigate('Profile', { accessToken }));
// Alert.alert('LogIn Successfully ' + + this.props.navigation.navigate('Profile'));
})
.catch((error) => {
console.log(error);
this.removeToken();
Alert.alert(' Login Failed try again , If you do not have an account, sign up first !');
});
}
}
render() {
if (this.state.userId !== '' || this.state.userId !== null) {
return (
// console.log('if block - No data found profile => LogIn now.:' + this.state.userId)
// Alert.alert('Please LogIn Now')
<View style={styles.container}>
<View style={styles.ifContainer}>
<Text style={styles.formHeader}>Thank you - you are already logedIn Got to</Text>
<TouchableOpacity style={[styles.buttonContainer, styles.greenButton]} onPress={() => this.props.navigation.navigate('Home')}>
<Text style={styles.buttonText}>Home</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.blueButton]} onPress={() => this.props.navigation.navigate('Profile')}>
<Text style={styles.buttonText}>Profile</Text>
</TouchableOpacity>
</View>
</View>
// Alert.alert('You are already LogedIn ' + this.props.navigation.navigate('Profile'))
)
} else {
return (
<View styel={styles.container}>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text style={styles.formHeader}>LogIn</Text>
<View style={styles.inputContainer}>
<TextInput style={styles.inputs}
type='number'
value={this.state.mobile}
name="mobile"
maxLength={10}
placeholder="mobile"
keyboardType="numeric"
underlineColorAndroid='transparent'
onChangeText={(mobile) => this.setState({ mobile })} />
<Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/color/48/000000/android.png' }} />
</View>
<View style={styles.inputContainer}>
<TextInput style={styles.inputs}
type='password'
value={this.state.password}
name="password"
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(password) => this.setState({ password })} />
<Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/color/40/000000/password.png' }} />
</View>
<TouchableOpacity style={[styles.buttonContainer, styles.greenButton]} onPress={() => { this.logInUser() }}>
<Text style={styles.buttonText}>LogIn</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.blueButton]} onPress={() => this.props.navigation.navigate('Register')}>
<Text style={styles.buttonText}>Register</Text>
</TouchableOpacity>
</View >
</View>
)
}
}// Render Ends
} // Class Ends
const resizeMode = 'center';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#DCDCDC',
},
formHeader: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 20,
fontSize: 30,
backgroundColor: 'transparent',
color: 'black',
},
inputContainer: {
borderBottomColor: '#F5FCFF',
backgroundColor: '#FFFFFF',
borderRadius: 30,
borderBottomWidth: 1,
width: 300,
height: 45,
marginBottom: 20,
flexDirection: 'row',
alignItems: 'center',
shadowColor: "#808080",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
inputs: {
height: 45,
marginLeft: 16,
borderBottomColor: '#FFFFFF',
flex: 1,
fontSize: 20,
},
inputIcon: {
width: 30,
height: 30,
marginRight: 15,
justifyContent: 'center'
},
buttonContainer: {
height: 45,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 20,
width: 300,
borderRadius: 30,
backgroundColor: 'transparent'
},
greenButton: {
backgroundColor: "#00a63f",
shadowColor: "#808080",
shadowOffset: {
width: 0,
height: 9,
},
shadowOpacity: 0.50,
shadowRadius: 12.35,
elevation: 19,
},
blueButton: {
backgroundColor: "#4e8bd1",
shadowColor: "#808080",
shadowOffset: {
width: 0,
height: 9,
},
shadowOpacity: 0.50,
shadowRadius: 12.35,
elevation: 19,
},
buttonText: {
color: 'white',
fontSize: 20,
fontWeight: 'bold',
textShadowColor: 'rgba(0, 0, 0, 0.75)',
textShadowOffset: { width: -1, height: 1 },
textShadowRadius: 10
},
bgImage: {
flex: 1,
resizeMode,
position: 'absolute',
width: '100%',
height: '100%',
justifyContent: 'center',
}
});
LogInScreen.navigationOptions = {
title: 'LogIn',
};
please check the code and let me know if i wrote anything wrong in the code .
change if condition in render from or to and:
if (this.state.userId !== '' && this.state.userId !== null) {....}
Recommended: Change method get_Id to arrow function signature:
get_Id = async ()=> {
try {
const userId = await AsyncStorage.getItem('USER_ID') // (STORAGE_KEY)
if (userId !== '' || userId !== null) {
this.setState({ userId: userId })
console.log('profile get_id id: =>', userId)
// this.getUserDetails(userId)
} else {
console.log('profile get_id id: => user_id=null')
Alert.alert('No user profile found LogIn Now ' + this.props.navigation.navigate('LogIn'))
}
} catch (error) {
alert('Failed to load profile get_Id() user_id.')
}
}
Following is my minimal working example. It is 3 basic screens, and a Drawer screen. In the render() method of the DrawerScreen I am populating the drawer screen with the navigation items from the tabs array.
When I set the flex value of the navigationItem everything starts to behave weirdly.
The items don't show up in the drawer screen when reloading the app most of the time
When the items do show up, they disappear after they have been tapped on.
If the navigationItem style in the Stylesheet has no flex value, it works as expected. I don't understand what is happening and have no idea how to fix this.
Code:
const packageName = 'com.rnplayground';
class FirstTab extends React.Component {
render(){
console.log(this.props)
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>FirstTab</Text>
</View>
)
};
}
class SecondTab extends React.Component {
render(){
console.log(this.props)
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>SecondTab</Text>
</View>
)
};
}
class ThirdTab extends React.Component {
render(){
console.log(this.props)
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>ThirdTab</Text>
</View>
)
};
}
class DrawerScreen extends React.Component {
render(){
const {tabs} = this.props;
return(
<View style={styles.navigationContainer}>
{tabs.map((route, index) => {
const navigationLabel = route.title;
return (
<TouchableHighlight
key={route.screen}
onPress={() => {
this.props.navigator.switchToTab({
tabIndex: index
});
}}
underlayColor='blue'
>
<View style={styles.navigationItem}>
<Text style={styles.navigationLabel}>
{navigationLabel}
</Text>
</View>
</TouchableHighlight>
);
})}
</View>
)
};
}
function registerScreens(){
Navigation.registerComponent(`${packageName}.FirstTab`, () => FirstTab );
Navigation.registerComponent(`${packageName}.SecondTab`, () => SecondTab );
Navigation.registerComponent(`${packageName}.ThirdTab`, () => ThirdTab );
Navigation.registerComponent(`${packageName}.DrawerScreen`, () => DrawerScreen );
}
function startApp() {
registerScreens();
const tabs = [
{
screen: `${packageName}.FirstTab`,
title: 'FirstTab',
icon: require('./image.png'),
navigatorStyle: {
tabBarHidden: true,
},
},
{
screen: `${packageName}.SecondTab`,
title: 'SecondTab',
icon: require('./image.png'),
navigatorStyle: {
tabBarHidden: true,
},
},
{
screen: `${packageName}.ThirdTab`,
title: 'ThirdTab',
icon: require('./image.png'),
navigatorStyle: {
tabBarHidden: true,
},
},
];
Navigation.startTabBasedApp(
{
tabs: tabs,
drawer: {
left: {
screen: `${packageName}.DrawerScreen`,
passProps: {
tabs: tabs
},
fixedWidth: 800,
}
},
tabsStyle:{
tabBarHidden: true,
}
},
);
}
startApp();
Stylesheet:
const styles = StyleSheet.create({
navigationContainer:{
flex: 1,
width: '100%',
backgroundColor: 'white',
},
navigationItem: {
flex: 1,
}
});
Here is an imgur link showing the behavior in question.
Using flexbox in React Native I'm having a lot of trouble trying to do the following seemingly simple task:
I have two item inside a container. I want one centered, and the other one to lie directly to the left of it.
You can change the flex size properties of the two outer components, and as long as they are the same, the middle item will be centered.
Notice the justifyContent:'flex-end' property of the first component. This styling is what is making the item lie directly to the left of the middle item.
<View style={styles.container}>
<View style={styles.component1}>
<Text>Right</Text>
</View>
<View style={styles.component2}>
<Text style={{ textAlign:'center' }}>I am the Center Component</Text>
</View>
<View style={styles.component3}></View>
</View>
container: {
flexDirection:'row',
flex:1,
marginTop:60
},
component1: {
flex:1,
flexDirection: 'row',
justifyContent: 'flex-end',
height:80
},
component2: {
flex:1,
height:80,
backgroundColor: 'red',
justifyContent:'center'
},
component3: {
flex:1,
}
Also, the entire code is below:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
var SampleApp = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.component1}>
<Text>Right</Text>
</View>
<View style={styles.component2}>
<Text style={{ textAlign:'center' }}>I am the Center Component</Text>
</View>
<View style={styles.component3}></View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flexDirection:'row',
flex:1,
marginTop:60
},
component1: {
flex:1,
flexDirection: 'row',
justifyContent: 'flex-end',
height:80
},
component2: {
flex:1,
height:80,
backgroundColor: 'red',
justifyContent:'center'
},
component3: {
flex:1,
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);