Custom components does not work in React Native - javascript

I am new to react native and trying to make a small user input form, but my code does not work well.
I made a class that will create label and text input, but style does not work for my class, Form1. The class in the same file App.js worked, but importing from another js file did not.
Can someone help me to figure out the solution and why it happens?
App.js
import React, { useState } from 'react';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
import Form1 from './Parts/Form1';
export default function App() {
const [name, setName] = useState('Haruku');
const [age, setAge] = useState('30');
return (
<View style={styles.container}>
<StatusBar style="auto" />
<View>
<Text style={styles.centerBox} borderWidth="1">Enter name: </Text>
<TextInput
style={styles.input}
placeholder='Example'
onChangeText={(val) => setName(val)} />
<Form1 />
<Text>name: {name}, age: {age}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
input: {
borderWidth: 1,
borderColor: '#777',
alignItems: 'center',
justifyContent: 'center',
padding: 8,
margin: 10,
width: 200,
},
centerBox: {
alignSelf: 'center',
textAlign: 'center',
borderWidth: 1,
width: 150,
},
buttonContainer: {
marginTop: 20,
backgroundColor: "#0000FF",
},
});
Form1.js
import React from 'react';
import { StyleSheet, Text, View,TextInput } from 'react-native';
class Form1 extends React.Component {
render() {
return (
<View>
<Text style={styles2.centerBox}>Age: </Text>
<TextInput style={styles2.input} placeholder='Example' />
</View>
)
}
}
const styles2 = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
input: {
borderWidth: 1,
borderColor: '#777',
alignItems: 'center',
justifyContent: 'center',
padding: 8,
margin: 10,
width: 200,
placeholder: "Ex",
},
centerBox: {
alignSelf: 'center',
textAlign: 'center',
alignItems: 'center',
},
});
export default Form1;

We should import the React when we are creating any component that returns JSX.
Have a try by adding the below import statement on the top of the Form1.js
import React from 'react';

Related

Which component should I use class or functional?

I'm trying to use react-native-camera and I want to send tokens from the first page to the camera page.
how can I get a token on the camera page? I am not sure how to solve this problem, I tried to change the camera page to function based component but I get more errors :) so I'd be very happy if you guys help me out
the first page is function-based component
import React from 'react';
import {View, Text, TouchableOpacity, ActivityIndicator} from 'react-native';
const first = () => {
const token = '12345678';
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{isData?(
<TouchableOpacity
onPress={() => {
navigation.navigate('cameraV2', {token:token});
}}
style={{
height: 50,
width: '80%',
backgroundColor: '#f45f00',
alignItems: 'center',
justifyContent: 'center',
}}>
<Text style={{fontWeight: 'bold', fontSize: 18}}>
Giriş için tıklayın
</Text>
</TouchableOpacity>
):(
<ActivityIndicator size='large' color='#0f0' />
)}
</View>
);
};
export default first;
camera page is class based component
import React, {Component} from 'react';
import {Button, Text, View} from 'react-native';
import {RNCamera} from 'react-native-camera';
class cameraV2 extends Component {
navigation = this.props.navigation;
constructor(props) {
super(props);
this.camera = null;
this.barcodeCodes = [];
this.state = {
token:this.navigation.token,
is_camera: 0,
is_loading: 0,
barcodes: [],
camera: {
type: RNCamera.Constants.Type.back,
flashMode: RNCamera.Constants.FlashMode.auto,
},
};
}
barcodeRecognized = ({barcodes}) => {
barcodes.forEach(barcode => {
if(barcode.type!=='UNKNOWN_FORMAT'){
console.log(barcode.data)
this.setState({barcodes});
}
});
};
render() {
return (
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
defaultTouchToFocus
flashMode={this.state.camera.flashMode}
mirrorImage={false}
//onBarCodeRead={this.onBarCodeRead.bind(this)}
onGoogleVisionBarcodesDetected={this.barcodeRecognized}
onFocusChanged={() => {}}
onZoomChanged={() => {}}
permissionDialogTitle={'Permission to use camera'}
permissionDialogMessage={
'We need your permission to use your camera phone'
}
style={styles.preview}
type={this.state.camera.type}
/>
<View style={[styles.overlay, styles.topOverlay]}>
<Text style={styles.scanScreenMessage}>Please scan the barcode.</Text>
<Text style={styles.scanScreenMessage}>token: {this.state.token} </Text>
</View>
<View style={[styles.overlay, styles.bottomOverlay]}>
<Button
onPress={() =>
this.navigation.navigate('second', {
barcode: this.state.barcodes,
token: token,
})
}
style={styles.enterBarcodeManualButton}
title="Enter Barcode"
/>
</View>
</View>
);
}
}
const styles = {
container: {
flex: 1,
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
},
overlay: {
position: 'absolute',
padding: 16,
right: 0,
left: 0,
alignItems: 'center',
},
topOverlay: {
top: 0,
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
bottomOverlay: {
bottom: 0,
backgroundColor: 'rgba(0,0,0,0.4)',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
enterBarcodeManualButton: {
padding: 15,
backgroundColor: 'white',
borderRadius: 40,
},
scanScreenMessage: {
fontSize: 14,
color: 'white',
textAlign: 'center',
alignItems: 'center',
justifyContent: 'center',
},
};
export default cameraV2;
You just need to initialise the state with token value from route params obtained from props instead of navigation
this.state = {
token: this.props.route.params.token,
is_camera: 0,
is_loading: 0,
barcodes: [],
camera: {
type: RNCamera.Constants.Type.back,
flashMode: RNCamera.Constants.FlashMode.auto,
},
};
}
P.S You do not need to convert the entire component to functional
component just for using params

Styles not working properly in an specific page

I'm a Newbie in React Native. And I'm trying to create a login screen with a normal "ENTER" button and Facebook and google "login with" buttons. For the social network buttons, I used expo vector-icons, but for the normal button, I created a .js file to host the button code so I can use it on other pages. The problem is: the button's styles are not being applied when I'm using it on this specific screen, for some reason... Am I doing something wrong?
Here is the code for the login screen:
import React from 'react';
import { View, Text, KeyboardAvoidingView, TextInput, StyleSheet } from 'react-native';
import { FontAwesome, Zocial } from '#expo/vector-icons';
import { SafeAreaView } from 'react-native-safe-area-context';
import SubmitButton from '../../shared/SubmitButton';
import FocusAwareStatusBar from '../../shared/StatusBar';
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: '#fafafa',
alignItems: 'center',
justifyContent: 'flex-start',
paddingHorizontal: 16
},
loginform: {
alignSelf: "stretch",
marginTop: 64,
},
inputs: {
alignSelf: "stretch",
fontFamily: "Roboto_400Regular",
fontSize: 14,
color: "#000",
borderBottomColor: '#dcdcdc',
borderBottomWidth: 0.8,
paddingBottom: 8,
paddingLeft: 12,
},
loginSocialNetworkContainer: {
justifyContent: "center",
alignSelf: "center",
backgroundColor: '#fff',
elevation: 6,
borderRadius: 6,
marginBottom: 8,
},
loginSocialNetwork: {
alignContent: "center",
justifyContent: "center",
width: 232,
height: 40,
borderRadius: 2,
},
loginSocialNetworkText: {
fontSize: 12,
fontFamily: "Roboto_400Regular",
color: "#f7f7f7",
},
});
export default function Login({ navigation }) {
return (
<SafeAreaView style={{ flex: 1 }}>
<FocusAwareStatusBar barStyle='light-content' backgroundColor='#88c9bf' />
<KeyboardAvoidingView style={styles.background}>
<View style={styles.loginform}>
<TextInput style={{ ...styles.inputs, marginBottom: 20 }}
placeholder="Nome de usuário"
autoCorrect={false}
onChangeText={() => { }}
/>
<TextInput style={{ ...styles.inputs, marginBottom: 52 }}
placeholder="Senha"
autoCorrect={false}
secureTextEntry={true}
onChangeText={() => { }}
/>
<SubmitButton text='ENTRAR' onPress={() => { }} />
<View style={{ ...styles.loginSocialNetworkContainer, marginTop: 72 }}>
<FontAwesome.Button name='facebook-square' style={styles.loginSocialNetwork} size={17.5} iconStyle={{ color: '#f7f7f7' }} backgroundColor="#194f7c" onPress={() => { }}>
<Text style={styles.loginSocialNetworkText}>ENTRAR COM FACEBOOK</Text>
</FontAwesome.Button>
</View>
<View style={styles.loginSocialNetworkContainer}>
<Zocial.Button name='googleplus' style={styles.loginSocialNetwork} size={15} iconStyle={{ color: '#f7f7f7', marginRight: 9.3, marginLeft: 0.3 }} backgroundColor="#f25f5c" onPress={() => { }}>
<Text style={{ ...styles.loginSocialNetworkText, paddingRight: 14 }}>ENTRAR COM GOOGLE</Text>
</Zocial.Button>
</View>
</View>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
And here is the SubmitButton's code:
import React from 'react';
import { View, StyleSheet, TouchableOpacity, Text } from 'react-native';
export default function SubmitButton({ text, onPress, color }) {
return (
<View style={styles.container}>
<TouchableOpacity onPress={onPress}>
<View style={ color != null ? {...styles.button, backgroundColor: color} :styles.button} >
<Text style={styles.buttonText}>{text}</Text>
</View>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignSelf: "center",
backgroundColor: '#fafafa',
elevation: 6,
borderRadius: 2,
width: 232,
height: 40,
},
button: {
justifyContent: "center",
alignItems: "center",
backgroundColor: '#88c9bf',
width: 232,
height: 40,
borderRadius: 2,
},
buttonText: {
fontFamily: "Roboto_400Regular",
fontSize: 12,
textTransform: 'uppercase',
textAlign: "center",
color: '#434343',
}
});
As we can see, the elevation is not getting applied nor the button can be
pressed:
Import React in your login page
import React from 'react';
import { View, Text, KeyboardAvoidingView, TextInput, StyleSheet } from 'react-native';
import { FontAwesome, Zocial } from '#expo/vector-icons';
import { SafeAreaView } from 'react-native-safe-area-context';
import SubmitButton from '../../shared/SubmitButton';
import FocusAwareStatusBar from '../../shared/StatusBar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const LotsOfStyles = () => {
return (
<View style={styles.container}>
<Text style={styles.red}>just red</Text>
<Text style={styles.bigBlue}>just bigBlue</Text>
<Text style={[styles.bigBlue, styles.red]}>bigBlue, then red</Text>
<Text style={[styles.red, styles.bigBlue]}>red, then bigBlue</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
marginTop: 50,
},
bigBlue: {
color: 'blue',
fontWeight: 'bold',
fontSize: 30,
},
red: {
color: 'red',
},
});
export default LotsOfStyles;

React Navigation header not visible when using Drawer Navigation

Below is my code which uses drawer navigation. But header given on HomeScreen disappears and is not visible.
I am only using drawer navigation and no nesting of navigation is going on.
App.js file -
import React, { Component } from "react";
import { Platform, StyleSheet, Text, View } from "react-native";
import MyApp from "./src/router/router";
export default class App extends Component {
render() {
return <MyApp />;
}
}
router.js file -
import {
createDrawerNavigator,
createAppContainer
} from "react-navigation";
import Sidebar from "../components/Sidebar/Sidebar";
import HomeScreen from "../components/HomeScreen/HomeScreen";
const MyDrawerNavigator = createDrawerNavigator(
{
Home: {
screen: HomeScreen
}
},
{
contentComponent: Sidebar,
drawerWidth: 200,
}
);
const App = createAppContainer(MyDrawerNavigator);
export default App;
HomeScreen.js file -
import React, { Component } from "react";
import {
Text,
View,
ScrollView,
TextInput,
TouchableOpacity,
Image
} from "react-native";
import { Calendar } from "react-native-calendars";
import ham from "../../assets/images/ham.png";
export default class HomeScreen extends Component {
static navigationOptions = {
drawerLabel: "Maruti Hotel Management",
headerStyle: {
backgroundColor: "#ED5A6C"
},
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold",
flex: 1,
textAlign: "center"
}
};
state = {
markedDate: {}
};
dateSelectHandler = date => {
let selectedDate = date.dateString;
this.setState({
markedDate: {
[selectedDate]: {
selected: true,
marked: true,
selectedColor: "#ED5A6C"
}
}
});
};
render() {
return (
<ScrollView style={{ flex: 1 }}>
<Calendar
style={{ flex: 1 }}
// Initially visible month. Default = Date()
onDayPress={day => {
console.log(day);
this.dateSelectHandler(day);
}}
markedDates={this.state.markedDate}
theme={{
"stylesheet.calendar.header": {
week: {
marginTop: 5,
flexDirection: "row",
justifyContent: "space-around",
backgroundColor: "#ED5A6C",
color: "red"
},
dayHeader: {
marginTop: 2,
marginBottom: 7,
width: 32,
textAlign: "center",
color: "#fff"
}
},
calendarBackground: "#F5A5AE",
arrowColor: "#ED5A6C",
monthTextColor: "#ED5A6C",
dayTextColor: "#ED5A6C",
todayTextColor: "blue"
}}
/>
<View
style={{
flex: 1,
backgroundColor: "#F07886",
alignItems: "center",
paddingTop: "2%",
paddingBottom: "10%"
}}
>
<Text
style={{
textAlign: "center",
color: "#FFF",
fontWeight: "500",
fontSize: 17
}}
>
Total Income (गल्ला)
</Text>
<TextInput
style={{
borderBottomColor: "#fff",
borderBottomWidth: 1,
paddingRight: "3%",
paddingLeft: "3%",
marginBottom: "2%",
width: "80%"
}}
editable={true}
maxLength={40}
placeholder="Rs"
/>
<TouchableOpacity style={{ width: "80%", marginTop: "2%" }}>
<View
style={{
borderRadius: 5,
backgroundColor: "#D85263",
paddingTop: 10,
paddingBottom: 10,
// paddingLeft: 15,
// paddingRight: 15,
justifyContent: "center",
alignItems: "center"
}}
>
<Text
style={{
width: "80%",
textAlign: "center",
color: "#fff",
fontWeight: "700",
fontSize: 16,
letterSpacing: 2
}}
>
Submit
</Text>
</View>
</TouchableOpacity>
</View>
</ScrollView>
);
}
}
Please help as I am stuck and already viewed similar questions but with no luck
Use generic header component and implement it in each screen where header is required. Pass header name as prop from the screen
Header Component:
class PageHeader extends Component {
<Header>
<Left>
<Button
transparent
onPress={() => this.props.navigation.openDrawer()}
>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>{this.props.title}</Title>
</Body>
<Right />
</Header>
}
export default PageHeader;
Sample Screen:
<Container style={styles.container}>
<PageHeader title="Home" />
<View>
// screen view
</View>
</Container>
The best way I found to use and customize headers for different screens is by using the Header component by react-native-elements. You just add the component to each screen that you want the header on. Also, dont forget to do header: null on your stackNavigator so it wont show 2 headers on the screen.
Example below:
<React.Fragment>
<Header
statusBarProps={{ barStyle: 'light-content' }}
barStyle="light-content"
leftComponent={
<SimpleIcon
name="menu"
color="#34495e"
size={20}
/>
}
centerComponent={{ text: 'HOME', style: { color: '#34495e' } }}
containerStyle={{
backgroundColor: 'white',
justifyContent: 'space-around',
}}
/>
</React.Fragment>

REACT-NATIVE SyntaxError unterminated JSX contents (57:41)

Help, Im trying code an app an I can't seem to get past this error.
var React = require('react-native');
var {
View,
Text,
StyleSheet
} = React;
var styles = StyleSheet.create({
mainContainer: {
flex: 1,
padding: 30,
marginTop: 65,
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: '#48BBEC'
},
title: {
marginBottom: 20,
fontSize: 25,
textAlign: 'center',
color: '#fff'
},
searchInput: {
height: 50,
padding: 4,
marginRight: 5,
fontSize: 23,
borderWidth: 1,
borderColor: 'white',
borderRadius: 8,
color: 'white'
},
buttonText: {
fontSize: 18,
color: '#111',
alignSelf: 'center'
},
button: {
height: 45,
flexDirection: 'row',
backgroundColor: 'white',
borderColor: 'white',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
marginTop: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
});
class Main extends React.Component{
render(){
return (
<View style={styles.mainContainer}>
<Text> Testing the Router </Text>
</View>
)
}
};
module.exports = Main;
I believe the problem lies in this block
class Main extends React.Component{
render(){
return (
<View style={styles.mainContainer}>
<Text> Testing the Router </Text>
</View>
)
}
};
There error message is: SyntaxError /Users/tevinrivera/Rondeh/App/Components/Main.js: Unterminated JSX contents(57:41)
Your imports are wrong. You need to import React from 'react' and other things like View, Stylesheet etc from 'react-native'.
Something like will work:
import React from 'react';
import {
View,
Text,
StyleSheet
} from 'react-native';
Everything looks fine. Try changing this code
var React = require('react-native');
var {
View,
Text,
StyleSheet
} = React;
to this
const React = require('React');
const ReactNative = require('react-native');
const{
StyleSheet,
View,
Text
} = ReactNative;

React Native: <Text> won't render if placed inside <TouchableHighlight>

In the following code:
'use strict';
var React = require('react-native'),
{
AppRegistry,
StyleSheet,
Text,
View,
Component,
NavigatorIOS
} = React,
styles = StyleSheet.create({
container: {
padding: 30,
marginTop: 65,
alignItems: 'center'
},
button: {
height: 36,
flex: 1,
flexDirection: 'row',
backgroundColor: '#48BBEC',
borderColor: '#48BBEC',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
text: {
color: 'black',
backgroundColor: 'white',
fontSize: 30,
margin: 80
}
})
class Login extends Component {
render() {
return (
/*<TouchableHighlight
style={styles.button}
underlayColor='#99d9f4'>*/
<Text style={styles.text}>Login with Google</Text>
/*</TouchableHighlight>*/
)
}
}
module.exports = Login
The <Text> Login gets rendered only when the surrounding <TouchableHighlight> is commented out. What am I doing wrong?
You need to import 'TouchableHighlight'.
Add TouchableHighlight to your list of requires.
var React = require('react-native'),
{
AppRegistry,
StyleSheet,
Text,
View,
Component,
NavigatorIOS,
TouchableHighlight
} = React,
In order to use the tag, you have to import it in the destructuring assignment block just like Text and View.

Categories

Resources