why can't i import my custom component in react native - react-native
i created these components and i was trying to import them in App.js but it shows me an error message, i tried to change the export default class multiple times , i chaged the order of import lines to figure out if there'e an error in the importing of one of the components, but nothing changed and still shows me the same error message, how can i fix it
App.js
import React, { Component } from "react";
import {ActivityIndicator,Keyboard,KeyboardAvoidingView,StyleSheet} from "react-native";
import { theme } from './constants';
import Block from './app/components' ;
import Button from './app/components' ;
import Text from './app/components' ;
import Input from './app/components' ;
const VALID_EMAIL = "contact#react-ui-kit.com";
const VALID_PASSWORD = "subscribe";
export default class Login extends Component {
state = {
email: VALID_EMAIL,
password: VALID_PASSWORD,
errors: [],
loading: false
};
handleLogin() {
const { navigation } = this.props;
const { email, password } = this.state;
const errors = [];
Keyboard.dismiss();
this.setState({ loading: true });
// check with backend API or with some static data
if (email !== VALID_EMAIL) {
errors.push("email");
}
if (password !== VALID_PASSWORD) {
errors.push("password");
}
this.setState({ errors, loading: false });
if (!errors.length) {
navigation.navigate("Browse");
}
}
render() {
const { navigation } = this.props;
const { loading, errors } = this.state;
const hasErrors = key => (errors.includes(key) ? styles.hasErrors : null);
return (
<KeyboardAvoidingView style={styles.login} behavior="padding">
<Block padding={[0, theme.sizes.base * 2]}>
<Text h1 bold>
Login
</Text>
<Block middle>
<Input
label="Email"
error={hasErrors("email")}
style={[styles.input, hasErrors("email")]}
defaultValue={this.state.email}
onChangeText={text => this.setState({ email: text })}
/>
<Input
secure
label="Password"
error={hasErrors("password")}
style={[styles.input, hasErrors("password")]}
defaultValue={this.state.password}
onChangeText={text => this.setState({ password: text })}
/>
<Button gradient onPress={() => this.handleLogin()}>
{loading ? (
<ActivityIndicator size="small" color="white" />
) : (
<Text bold white center>
Login
</Text>
)}
</Button>
<Button onPress={() => navigation.navigate("Forgot")}>
<Text
gray
caption
center
style={{ textDecorationLine: "underline" }}
>
Forgot your password?
</Text>
</Button>
</Block>
</Block>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
login: {
flex: 1,
justifyContent: "center"
},
input: {
borderRadius: 0,
borderWidth: 0,
borderBottomColor: theme.colors.gray2,
borderBottomWidth: StyleSheet.hairlineWidth
},
hasErrors: {
borderBottomColor: theme.colors.accent
}
});
Block.js
import React, { Component } from "react";
import { StyleSheet, View, Animated } from "react-native";
import { theme } from "./constants";
export default class Block extends Component {
handleMargins() {
const { margin } = this.props;
if (typeof margin === "number") {
return {
marginTop: margin,
marginRight: margin,
marginBottom: margin,
marginLeft: margin
};
}
if (typeof margin === "object") {
const marginSize = Object.keys(margin).length;
switch (marginSize) {
case 1:
return {
marginTop: margin[0],
marginRight: margin[0],
marginBottom: margin[0],
marginLeft: margin[0]
};
case 2:
return {
marginTop: margin[0],
marginRight: margin[1],
marginBottom: margin[0],
marginLeft: margin[1]
};
case 3:
return {
marginTop: margin[0],
marginRight: margin[1],
marginBottom: margin[2],
marginLeft: margin[1]
};
default:
return {
marginTop: margin[0],
marginRight: margin[1],
marginBottom: margin[2],
marginLeft: margin[3]
};
}
}
}
handlePaddings() {
const { padding } = this.props;
if (typeof padding === "number") {
return {
paddingTop: padding,
paddingRight: padding,
paddingBottom: padding,
paddingLeft: padding
};
}
if (typeof padding === "object") {
const paddingSize = Object.keys(padding).length;
switch (paddingSize) {
case 1:
return {
paddingTop: padding[0],
paddingRight: padding[0],
paddingBottom: padding[0],
paddingLeft: padding[0]
};
case 2:
return {
paddingTop: padding[0],
paddingRight: padding[1],
paddingBottom: padding[0],
paddingLeft: padding[1]
};
case 3:
return {
paddingTop: padding[0],
paddingRight: padding[1],
paddingBottom: padding[2],
paddingLeft: padding[1]
};
default:
return {
paddingTop: padding[0],
paddingRight: padding[1],
paddingBottom: padding[2],
paddingLeft: padding[3]
};
}
}
}
render() {
const {
flex,
row,
column,
center,
middle,
left,
right,
top,
bottom,
card,
shadow,
color,
space,
padding,
margin,
animated,
wrap,
style,
children,
...props
} = this.props;
const blockStyles = [
styles.block,
flex && { flex },
flex === false && { flex: 0 }, // reset / disable flex
row && styles.row,
column && styles.column,
center && styles.center,
middle && styles.middle,
left && styles.left,
right && styles.right,
top && styles.top,
bottom && styles.bottom,
margin && { ...this.handleMargins() },
padding && { ...this.handlePaddings() },
card && styles.card,
shadow && styles.shadow,
space && { justifyContent: `space-${space}` },
wrap && { flexWrap: "wrap" },
color && styles[color], // predefined styles colors for backgroundColor
color && !styles[color] && { backgroundColor: color }, // custom backgroundColor
style // rewrite predefined styles
];
if (animated) {
return (
<Animated.View style={blockStyles} {...props}>
{children}
</Animated.View>
);
}
return (
<View style={blockStyles} {...props}>
{children}
</View>
);
}
}
export const styles = StyleSheet.create({
block: {
flex: 1
},
row: {
flexDirection: "row"
},
column: {
flexDirection: "column"
},
card: {
borderRadius: theme.sizes.radius
},
center: {
alignItems: "center"
},
middle: {
justifyContent: "center"
},
left: {
justifyContent: "flex-start"
},
right: {
justifyContent: "flex-end"
},
top: {
justifyContent: "flex-start"
},
bottom: {
justifyContent: "flex-end"
},
shadow: {
shadowColor: theme.colors.black,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 13,
elevation: 2
},
accent: { backgroundColor: theme.colors.accent },
primary: { backgroundColor: theme.colors.primary },
secondary: { backgroundColor: theme.colors.secondary },
tertiary: { backgroundColor: theme.colors.tertiary },
black: { backgroundColor: theme.colors.black },
white: { backgroundColor: theme.colors.white },
gray: { backgroundColor: theme.colors.gray },
gray2: { backgroundColor: theme.colors.gray2 }
});
Text.js
import React, { Component } from "react";
import { Text, StyleSheet } from "react-native";
import { theme } from "./constants";
export default class Typography extends Component {
render() {
const {
h1,
h2,
h3,
title,
body,
caption,
small,
size,
transform,
align,
// styling
regular,
bold,
semibold,
medium,
weight,
light,
center,
right,
spacing, // letter-spacing
height, // line-height
// colors
color,
accent,
primary,
secondary,
tertiary,
black,
white,
gray,
gray2,
style,
children,
...props
} = this.props;
const textStyles = [
styles.text,
h1 && styles.h1,
h2 && styles.h2,
h3 && styles.h3,
title && styles.title,
body && styles.body,
caption && styles.caption,
small && styles.small,
size && { fontSize: size },
transform && { textTransform: transform },
align && { textAlign: align },
height && { lineHeight: height },
spacing && { letterSpacing: spacing },
weight && { fontWeight: weight },
regular && styles.regular,
bold && styles.bold,
semibold && styles.semibold,
medium && styles.medium,
light && styles.light,
center && styles.center,
right && styles.right,
color && styles[color],
color && !styles[color] && { color },
// color shortcuts
accent && styles.accent,
primary && styles.primary,
secondary && styles.secondary,
tertiary && styles.tertiary,
black && styles.black,
white && styles.white,
gray && styles.gray,
gray2 && styles.gray2,
style // rewrite predefined styles
];
return (
<Text style={textStyles} {...props}>
{children}
</Text>
);
}
}
const styles = StyleSheet.create({
// default style
text: {
fontSize: theme.sizes.font,
color: theme.colors.black
},
// variations
regular: {
fontWeight: "normal"
},
bold: {
fontWeight: "bold"
},
semibold: {
fontWeight: "500"
},
medium: {
fontWeight: "500"
},
light: {
fontWeight: "200"
},
// position
center: { textAlign: "center" },
right: { textAlign: "right" },
// colors
accent: { color: theme.colors.accent },
primary: { color: theme.colors.primary },
secondary: { color: theme.colors.secondary },
tertiary: { color: theme.colors.tertiary },
black: { color: theme.colors.black },
white: { color: theme.colors.white },
gray: { color: theme.colors.gray },
gray2: { color: theme.colors.gray2 },
// fonts
h1: theme.fonts.h1,
h2: theme.fonts.h2,
h3: theme.fonts.h3,
title: theme.fonts.title,
body: theme.fonts.body,
caption: theme.fonts.caption,
small: theme.fonts.small
});
Button.js
import React, { Component } from "react";
import { StyleSheet, TouchableOpacity } from "react-native";
import { LinearGradient } from "react-native-linear-gradient";
import { theme } from "./constants";
class Button extends Component {
render() {
const {
style,
opacity,
gradient,
color,
startColor,
endColor,
end,
start,
locations,
shadow,
children,
...props
} = this.props;
const buttonStyles = [
styles.button,
shadow && styles.shadow,
color && styles[color], // predefined styles colors for backgroundColor
color && !styles[color] && { backgroundColor: color }, // custom backgroundColor
style
];
if (gradient) {
return (
<TouchableOpacity
style={buttonStyles}
activeOpacity={opacity}
{...props}
>
<LinearGradient
start={start}
end={end}
locations={locations}
style={buttonStyles}
colors={[startColor, endColor]}
>
{children}
</LinearGradient> */
</TouchableOpacity>
);
}
return (
<TouchableOpacity
style={buttonStyles}
activeOpacity={opacity || 0.8}
{...props}
>
{children}
</TouchableOpacity>
);
}
}
Button.defaultProps = {
startColor: theme.colors.primary,
endColor: theme.colors.secondary,
start: { x: 0, y: 0 },
end: { x: 1, y: 1 },
locations: [0.1, 0.9],
opacity: 0.8,
color: theme.colors.white
};
export default Button;
const styles = StyleSheet.create({
button: {
borderRadius: theme.sizes.radius,
height: theme.sizes.base * 3,
justifyContent: "center",
marginVertical: theme.sizes.padding / 3
},
shadow: {
shadowColor: theme.colors.black,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 10
},
accent: { backgroundColor: theme.colors.accent },
primary: { backgroundColor: theme.colors.primary },
secondary: { backgroundColor: theme.colors.secondary },
tertiary: { backgroundColor: theme.colors.tertiary },
black: { backgroundColor: theme.colors.black },
white: { backgroundColor: theme.colors.white },
gray: { backgroundColor: theme.colors.gray },
gray2: { backgroundColor: theme.colors.gray2 },
gray3: { backgroundColor: theme.colors.gray3 },
gray4: { backgroundColor: theme.colors.gray4 }
});
Input.js
import React, { Component } from "react";
import { StyleSheet, View, Animated } from "react-native";
import { theme } from "./constants";
export default class Block extends Component {
handleMargins() {
const { margin } = this.props;
if (typeof margin === "number") {
return {
marginTop: margin,
marginRight: margin,
marginBottom: margin,
marginLeft: margin
};
}
if (typeof margin === "object") {
const marginSize = Object.keys(margin).length;
switch (marginSize) {
case 1:
return {
marginTop: margin[0],
marginRight: margin[0],
marginBottom: margin[0],
marginLeft: margin[0]
};
case 2:
return {
marginTop: margin[0],
marginRight: margin[1],
marginBottom: margin[0],
marginLeft: margin[1]
};
case 3:
return {
marginTop: margin[0],
marginRight: margin[1],
marginBottom: margin[2],
marginLeft: margin[1]
};
default:
return {
marginTop: margin[0],
marginRight: margin[1],
marginBottom: margin[2],
marginLeft: margin[3]
};
}
}
}
handlePaddings() {
const { padding } = this.props;
if (typeof padding === "number") {
return {
paddingTop: padding,
paddingRight: padding,
paddingBottom: padding,
paddingLeft: padding
};
}
if (typeof padding === "object") {
const paddingSize = Object.keys(padding).length;
switch (paddingSize) {
case 1:
return {
paddingTop: padding[0],
paddingRight: padding[0],
paddingBottom: padding[0],
paddingLeft: padding[0]
};
case 2:
return {
paddingTop: padding[0],
paddingRight: padding[1],
paddingBottom: padding[0],
paddingLeft: padding[1]
};
case 3:
return {
paddingTop: padding[0],
paddingRight: padding[1],
paddingBottom: padding[2],
paddingLeft: padding[1]
};
default:
return {
paddingTop: padding[0],
paddingRight: padding[1],
paddingBottom: padding[2],
paddingLeft: padding[3]
};
}
}
}
render() {
const {
flex,
row,
column,
center,
middle,
left,
right,
top,
bottom,
card,
shadow,
color,
space,
padding,
margin,
animated,
wrap,
style,
children,
...props
} = this.props;
const blockStyles = [
styles.block,
flex && { flex },
flex === false && { flex: 0 }, // reset / disable flex
row && styles.row,
column && styles.column,
center && styles.center,
middle && styles.middle,
left && styles.left,
right && styles.right,
top && styles.top,
bottom && styles.bottom,
margin && { ...this.handleMargins() },
padding && { ...this.handlePaddings() },
card && styles.card,
shadow && styles.shadow,
space && { justifyContent: `space-${space}` },
wrap && { flexWrap: "wrap" },
color && styles[color], // predefined styles colors for backgroundColor
color && !styles[color] && { backgroundColor: color }, // custom backgroundColor
style // rewrite predefined styles
];
if (animated) {
return (
<Animated.View style={blockStyles} {...props}>
{children}
</Animated.View>
);
}
return (
<View style={blockStyles} {...props}>
{children}
</View>
);
}
}
export const styles = StyleSheet.create({
block: {
flex: 1
},
row: {
flexDirection: "row"
},
column: {
flexDirection: "column"
},
card: {
borderRadius: theme.sizes.radius
},
center: {
alignItems: "center"
},
middle: {
justifyContent: "center"
},
left: {
justifyContent: "flex-start"
},
right: {
justifyContent: "flex-end"
},
top: {
justifyContent: "flex-start"
},
bottom: {
justifyContent: "flex-end"
},
shadow: {
shadowColor: theme.colors.black,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 13,
elevation: 2
},
accent: { backgroundColor: theme.colors.accent },
primary: { backgroundColor: theme.colors.primary },
secondary: { backgroundColor: theme.colors.secondary },
tertiary: { backgroundColor: theme.colors.tertiary },
black: { backgroundColor: theme.colors.black },
white: { backgroundColor: theme.colors.white },
gray: { backgroundColor: theme.colors.gray },
gray2: { backgroundColor: theme.colors.gray2 }
});
the error
Error: Unable to resolve module ./components from C:\Users\DELL\wan_way_service_app\App.js:
None of these files exist:
* components(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
* components\index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
3 |
4 | import { theme } from './constants';
> 5 | import Button from './components' ;
| ^
6 | import Block from './components' ;
7 | import Text from './components' ;
8 | import Input from './components' ;
Are you exporting your component correctly?
OPTION 1 - if you are exporting one component per file, you can use the "export default" Example:
export default Class ClassName = () => {
return <View />;
}
and to import use
import ClassName from './app/components'
OPTION 2 - If there are several components, you have to export as a constant in this way
export Class ClassName = () => {
return <View />;
}
export Class OtherClassName = () => {
return <View />;
}
and to import use
import {ClassName, OtherClassName} from './app/components'
it depends on the way your folder structure is being created, by default and for a cleaner code the ideal is like this:
myAwesomeProject
src
| components
| | ComponentOne
| | | index.js
| | ComponentTwo
| | | index.js
and that way you can use the default export
Related
TypeError: (0, _app.initializeApp) is not a function
The app is just about taking data from text inputs and then uploading them on realtime database. It was working fine, but after I imported drawer navigator, it started giving the error above. I removed the dependency, but still it gives the same error.. I am new to react native... //config.js `import { initializeApp } from 'firebase/app' import { getDatabase } from 'firebase/database' function StartFirebase(){ const firebaseConfig = { apiKey: "", authDomain: "", databaseURL: "", projectId: "", storageBucket: "", messagingSenderId: "", appId: "" }; const app = initializeApp(firebaseConfig); return getDatabase(app); } export default StartFirebase; ` Below is the code of the main screen which contains the code for textinput and uploading data to database //createScreen.js `import React, { Component } from "react"; import { View, Text, StyleSheet, SafeAreaView, Platform, StatusBar, Image, ScrollView, TextInput, Dimensions, Button, Alert } from "react-native"; import { RFValue } from "react-native-responsive-fontsize"; import AppLoading from "expo-app-loading"; import * as Font from "expo-font"; import { useNavigation } from "#react-navigation/core"; import {ref,set,get,update,remove,child} from 'firebase/database' import StartFirebase from "./config"; const initialState = { name: "", phoneNumber: "", workYouDo: "", price: "", }; let customFonts = { "Bubblegum-Sans": require('./BubblegumSans-Regular.ttf') }; export default class CreateScreen extends Component { constructor(props) { super(props); this.state = { fontsLoaded: false, name: "a", phoneNumber: "0000000000", workYouDo: "a", price: "a", db:'' }; } async _loadFontsAsync() { await Font.loadAsync(customFonts); this.setState({ fontsLoaded: true }); } componentDidMount() { this._loadFontsAsync(); this.setState({ db:StartFirebase() }); } addStory() { let phoneNumberLength = this.state.phoneNumber.length if ( this.state.name && this.state.phoneNumber && this.state.workYouDo && this.state.price && phoneNumberLength == 10 ) { let storyData = { name: this.state.name, phoneNumber: this.state.phoneNumber, workYouDo: this.state.workYouDo, price: this.state.price, }; const db = this.state.db; set(ref(db,'users/'+this.state.name), { storyData }) .then(()=>{alert('data was added')}) this.props.navigation.navigate('Home') this.setState(initialState) } else { Alert.alert( "All fields are required!", 'Phone number should be of 10 digits without +91' ); } } render() { if (!this.state.fontsLoaded) { return <AppLoading />; } else { return ( <View style={styles.container} > <SafeAreaView style={styles.droidSafeArea} /> <View style={styles.appTitle}> <View style={styles.appIcon}> </View> <View style={styles.appTitleTextContainer}> <Text style={ styles.appTitleText } > Your Details </Text> </View> </View> <View style={styles.fieldsContainer}> <ScrollView> <View style={{ marginHorizontal: RFValue(10) }}> <TextInput style={ styles.inputFont } onChangeText={text => this.setState({name:text})} placeholder={"Name"} placeholderTextColor={'white'} value = {this.state.name} /> <TextInput style={[ styles.inputFont, styles.inputFontExtra, styles.inputTextBig ]} onChangeText={text => this.setState({phoneNumber:text})} placeholder={"PhoneNumber (Without +91)"} multiline={true} numberOfLines={1} maxLength={10} minLength = {10} type = {Number} keyboardType={"number-pad"} placeholderTextColor={ 'white' } value = {this.state.phoneNumber} /> <TextInput style={[ styles.inputFont, styles.inputFontExtra, styles.inputTextBig ]} onChangeText={text => this.setState({workYouDo:text})} placeholder={"WorkYouDo"} multiline={true} numberOfLines={3} placeholderTextColor={ 'white' } value = {this.state.workYouDo} /> <TextInput style={[ styles.inputFont, styles.inputFontExtra, styles.inputTextBig ]} onChangeText={text => this.setState({price:text})} placeholder={"price"} multiline={false} numberOfLines={1} placeholderTextColor={ 'white' } value = {this.state.price} /> </View> <View style={styles.submitButton}> <Button title="Submit" color="#841584" onPress={() => this.addStory()} /> </View> </ScrollView> </View> <View style={{ flex: 0.08 }} /> </View> ); } } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#15193c" }, // containerLight: { // flex: 1, // backgroundColor: "white" // }, droidSafeArea: { marginTop: Platform.OS === "android" ? StatusBar.currentHeight : RFValue(35) }, appTitle: { flex: 0.07, flexDirection: "row" }, appIcon: { flex: 0.3, justifyContent: "center", alignItems: "center" }, appTitleTextContainer: { flex: 0.7, justifyContent: "center" }, appTitleText: { color: "white", fontSize: RFValue(28), fontFamily: "Bubblegum-Sans" }, // appTitleTextLight: { // color: "black", // fontSize: RFValue(28), // fontFamily: "Bubblegum-Sans" // }, fieldsContainer: { flex: 0.85 }, inputFont: { height: RFValue(40), borderColor: "white", borderWidth: RFValue(1), borderRadius: RFValue(10), paddingLeft: RFValue(10), color: "white", fontFamily: "Bubblegum-Sans" }, // inputFontLight: { // height: RFValue(40), // borderColor: "black", // borderWidth: RFValue(1), // borderRadius: RFValue(10), // paddingLeft: RFValue(10), // color: "black", // fontFamily: "Bubblegum-Sans" // }, inputFontExtra: { marginTop: RFValue(15) }, inputTextBig: { textAlignVertical: "top", padding: RFValue(5) }, submitButton: { marginTop: RFValue(20), alignItems: "center", justifyContent: "center" } }); ` PlZZ HElP I have tried different ways of importing firebase, but none helped, I was expecting the error to go away but if intialize app would go then getData variable is not defined would appear..
Attempt to invoke virtual method in React-Native
When i run my react native code it gives error and says: Attempt to invoke virtual method 'com.facebook.react.bridge.CatalystInstance com.facebook.react.bridge.ReactContext.getCatalystInstance()' on a null object reference but in case when I run my code the second time it does not show this type of error and code runs successfully. what is the reason behind this error? Please suggest any answer. and my App.js files here.. import React, { Component } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Image, Platform, Animated } from 'react-native'; const Sliding_Drawer_Width = 300; export default class App extends Component { constructor() { super(); this.Animation = new Animated.Value(0); this.Sliding_Drawer_Toggle = true; } ShowSlidingDrawer = () => { if( this.Sliding_Drawer_Toggle === true ) { Animated.timing( this.Animation, { toValue: 1, duration: 500 } ).start(() => { this.Sliding_Drawer_Toggle = false; }); } else { Animated.timing( this.Animation, { toValue: 0, duration: 500 } ).start(() => { this.Sliding_Drawer_Toggle = true; }); } } render() { const Animation_Interpolate = this.Animation.interpolate( { inputRange: [ 0, 1 ], outputRange: [ -(Sliding_Drawer_Width - 32), 0 ] }); return ( <View style = { styles.MainContainer }> <Text style = {styles.TextStyle}> Components Which You Want To Show in App, Place Them Here. </Text> <Animated.View style = {[ styles.Root_Sliding_Drawer_Container, { transform: [{ translateX: Animation_Interpolate }]}]}> <View style = { styles.Main_Sliding_Drawer_Container }> <Text style = { styles.TextStyle } > Put All Your Components Here Which You Want To Show Inside Sliding Drawer. </Text> </View> <TouchableOpacity onPress = { this.ShowSlidingDrawer } style = {{ padding: 1 }}> <Image source = {{ uri : 'https://reactnativecode.com/wp-content/uploads/2017/11/Arrow_Icon.png' }} style = {{resizeMode: 'contain', width: 30, height: 30 }} /> </TouchableOpacity> </Animated.View> </View> ); } } const styles = StyleSheet.create( { MainContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' }, Root_Sliding_Drawer_Container: { position: 'absolute', flexDirection: 'row', left: 0, bottom: 0, top: (Platform.OS == 'ios') ? 20 : 0, width: Sliding_Drawer_Width, }, Main_Sliding_Drawer_Container: { flex: 1, backgroundColor: '#FFC107', paddingHorizontal: 10, justifyContent: 'center', alignItems: 'center' }, TextStyle: { fontSize: 25, padding: 10, textAlign: 'center', color: '#FF5722' } });
How to Hide a component in react native
Hi I have TextInput like this Now when i enter text inside TextInput and when i click on cancel then the it is clearing the text inside TextInput , Now along with this I want to hide Cancel when is is clicked. Here is my code import React, { Component } from 'react'; import { Dimensions, View, Animated, TextInput, TouchableOpacity, StyleSheet, } from 'react-native'; import colors from '../styles/colors'; const { width } = Dimensions.get('window'); const PADDING = 16; const SEARCH_FULL_WIDTH = width - PADDING * 2; //search_width when unfocused const SEARCH_SHRINK_WIDTH = width - PADDING - 90; //search_width when focused const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity); export default class Test extends Component { constructor(props) { super(props); this.state = { inputLength: new Animated.Value(SEARCH_FULL_WIDTH), cancelPosition: new Animated.Value(0), opacity: new Animated.Value(0), searchBarFocused: false, text: '', showCancel: true }; } onFocus = () => { Animated.parallel([ Animated.timing(this.state.inputLength, { toValue: SEARCH_SHRINK_WIDTH, duration: 250 }), Animated.timing(this.state.cancelPosition, { toValue: 16, duration: 400 }), Animated.timing(this.state.opacity, { toValue: 1, duration: 250 }), ]).start(); }; onBlur = () => { Animated.parallel([ Animated.timing(this.state.inputLength, { toValue: SEARCH_FULL_WIDTH, duration: 250 }), Animated.timing(this.state.cancelPosition, { toValue: 0, duration: 250 }), Animated.timing(this.state.opacity, { toValue: 0, duration: 250 }) ]).start(); }; clearInput = () => { this.textInputRef.clear(); //this.onFocus.bind(this); this.setState({ showCancel: !this.state.showCancel }); } _renderCancel() { if (this.state.showCancel) { return ( <AnimatedTouchable style={[styles.cancelSearch, { right: this.state.cancelPosition }]} onPress={(this.clearInput.bind(this))} > <Animated.Text style={[styles.cancelSearchText, { opacity: this.state.opacity, color: colors.darkBlue }]} onChangeText={text => this.setState({ text })} value={this.state.text} > Cancel </Animated.Text> </AnimatedTouchable> ); } else { return null; } } render() { const { searchBarFocused } = this.state; return ( <View style={styles.searchContainer}> <Animated.View style={[ styles.search, { width: this.state.inputLength, position: 'absolute', left: 16, alignSelf: 'center' }, searchBarFocused === true ? undefined : { justifyContent: 'center' } ]} > <TextInput style={styles.searchInput} onBlur={this.onBlur} onFocus={this.onFocus} placeholder="Enter condition, primary care, speciality" ref={(ref) => { this.textInputRef = ref; }} /> </Animated.View> <AnimatedTouchable style={[styles.cancelSearch, { right: this.state.cancelPosition }]} onPress={this.clearInput.bind(this)} > <Animated.Text style={[styles.cancelSearchText, { opacity: this.state.opacity, color: colors.darkBlue }]} onChangeText={text => this.setState({ text })} value={this.state.text} > Cancel </Animated.Text> </AnimatedTouchable> {this._renderCancel() } </View> ); } } const styles = StyleSheet.create({ searchContainer: { flexDirection: 'row', height: 72, borderColor: colors.light_green, paddingTop: 100 }, search: { height: 40, width: '100%', marginTop: 5, borderRadius: 6, alignItems: 'flex-start', justifyContent: 'flex-start', borderColor: colors.light_green, fontSize: 20, borderWidth: 1, }, cancelSearch: { position: 'absolute', marginHorizontal: 16, textAlign: 'center', justifyContent: 'center', alignSelf: 'center', color: colors.darkBlue } }); can anyone help me how to hide Cancel when it is clicked. when cancel is clicked i want my original TextInput to be like this
set the style to following : style={{ opacity: this.state.isVisible ? 1 : 0 }} and set state isVisibile accordingly to make it visible/hidden.
If you are trying to implement the clear text then you can use clearButtonMode. clearButtonMode Else if you are using state i.e showCancel you can use as {showCancel? <CancelButton/> : <View/>}
How to play video in full screen react-native android
Im trying to play full screen video using react native video, how can I play video full screen for both android and ios?in my case ios playing full screen correctly and in android video is stretched. for landscape mode I used transform: [{ rotate: '90deg' }], its works but in android the video screen in stretched Your help is highly appreciated. here is my code return ( <View onLayout={this.onLayout.bind(this)} style={styles.fullScreen} key={this.state.key}> <View style={styles.backButtonWrapper}> <TouchableOpacity onPress={() => this.props.navigation.goBack()}> <Image source={Share} /> </TouchableOpacity> </View> <TouchableOpacity style={styles.videoView} onPress={this.playOrPauseVideo.bind(this, paused)}> <Video ref={videoPlayer => this.videoPlayer = videoPlayer} onEnd={this.onVideoEnd.bind(this)} onLoad={this.onVideoLoad.bind(this)} onProgress={this.onProgress.bind(this)} source={{ uri: this.props.detailedWorkout.videoLink }} paused={paused} volume={Math.max(Math.min(1, volume), 0)} resizeMode="none" style={styles.videoContainer} /> {paused && <View style={styles.pauseImageWrapper}> <Image style={styles.videoIcon} source={PlayButton} /> </View> } </TouchableOpacity> </View> ); } const styles = StyleSheet.create({ container: { flex: 1 }, backgroundVideo: { position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, }, fullScreen: { flex: 1, backgroundColor: "white" }, videoView: { flex: 1, justifyContent: "center", alignItems: "center" }, videoContainer: { width: Dimensions.get('window').height, height: Dimensions.get('window').width, minWidth: Dimensions.get('window').height, minHeight: Dimensions.get('window').width, width: Dimensions.get('screen').height, height: Dimensions.get('screen').width, transform: [{ rotate: '90deg' }], }, videoIcon: { width: 50, height: 50 }, pauseImageWrapper: { alignItems: 'center', alignSelf: 'center', position: "absolute", }, backButtonWrapper: { backgroundColor: 'red', position: 'absolute', zIndex: 1, alignSelf: "flex-end" } });
I solve the issue using react-native-orientation.I'll post my code for anyone who having this issue.Cheers thanks for your help import React, { Component, PropTypes } from "react"; import { View, Dimensions, StyleSheet, TouchableOpacity, Image, StatusBar, Platform, } from "react-native"; import { Share, PlayButton } from "../../config/images"; import { TextLogo, IconWithCount, DefaultIcon, ClickableIcon, } from "../../mixing/UI"; import { WorkoutDetail, KeyValueText, DetailText, ProgressController } from "../../components"; import Orientation from "react-native-orientation"; import Video from "react-native-video" const width = Dimensions.get("window").width; const height = Dimensions.get("window").height; let FORWARD_DURATION = 7; export default class VideoPlayer extends Component { constructor(props, context, ...args) { super(props, context, ...args); this.state = { paused: false }; } componentDidMount() { Orientation.lockToLandscapeLeft(); } componentWillUnmount() { Orientation.lockToPortrait(); } componentWillMount() { StatusBar.setHidden(true); Orientation.lockToLandscapeLeft(); } onVideoEnd() { this.videoPlayer.seek(0); this.setState({ key: new Date(), currentTime: 0, paused: true }); } onVideoLoad(e) { this.setState({ currentTime: e.currentTime, duration: e.duration }); } onProgress(e) { this.setState({ currentTime: e.currentTime }); } playOrPauseVideo(paused) { this.setState({ paused: !paused }); } onBackward(currentTime) { let newTime = Math.max(currentTime - FORWARD_DURATION, 0); this.videoPlayer.seek(newTime); this.setState({ currentTime: newTime }) } onForward(currentTime, duration) { if (currentTime + FORWARD_DURATION > duration) { this.onVideoEnd(); } else { let newTime = currentTime + FORWARD_DURATION; this.videoPlayer.seek(newTime); this.setState({ currentTime: newTime }); } } getCurrentTimePercentage(currentTime, duration) { if (currentTime > 0) { return parseFloat(currentTime) / parseFloat(duration); } else { return 0; } } onProgressChanged(newPercent, paused) { let { duration } = this.state; let newTime = newPercent * duration / 100; this.setState({ currentTime: newTime, paused: paused }); this.videoPlayer.seek(newTime); } onLayout(e) { const { width, height } = Dimensions.get('window') } goBack = () => { this.props.navigation.goBack(); Orientation.lockToPortrait(); } // navigation options static navigationOptions = { header: null } // render render() { let { onClosePressed, video, volume } = this.props; let { currentTime, duration, paused } = this.state; const completedPercentage = this.getCurrentTimePercentage(currentTime, duration) * 100; return ( <View onLayout={this.onLayout.bind(this)} style={styles.fullScreen} key={this.state.key}> <View style={styles.backButtonWrapper}> <TouchableOpacity onPress={() => this.goBack()}> <Image source={Share} /> </TouchableOpacity> </View> <TouchableOpacity style={styles.videoView} onPress={this.playOrPauseVideo.bind(this, paused)}> <Video ref={videoPlayer => this.videoPlayer = videoPlayer} onEnd={this.onVideoEnd.bind(this)} onLoad={this.onVideoLoad.bind(this)} onProgress={this.onProgress.bind(this)} source={{ uri: this.props.detailedWorkout.videoLink }} paused={paused} volume={Math.max(Math.min(1, volume), 0)} resizeMode="none" style={Platform.OS === "android" ? styles.videoContainerAndroid : styles.videoContainerIOS} /> {paused && <View style={styles.pauseImageWrapper}> <Image style={styles.videoIcon} source={PlayButton} /> </View> } </TouchableOpacity> </View> ); } } // styles const styles = StyleSheet.create({ fullScreen: { flex: 1, backgroundColor: "black" }, videoView: { flex: 1, justifyContent: "center", alignItems: "center" }, videoContainerAndroid: { height: "100%", width: "100%" }, videoContainerIOS: { width: Dimensions.get('window').height, height: Dimensions.get('window').width, minWidth: Dimensions.get('window').height, minHeight: Dimensions.get('window').width, width: Dimensions.get('screen').height, height: Dimensions.get('screen').width, transform: [{ rotate: '90deg' }], }, videoIcon: { width: 50, height: 50 }, pauseImageWrapper: { alignItems: 'center', alignSelf: 'center', position: "absolute", }, backButtonWrapper: { backgroundColor: 'red', position: 'absolute', zIndex: 1, alignSelf: "flex-end" } });
Try resizeMode="contain" (documentation)
How to show text (YES/NO) inside a switch in react-native
I am new to react-native. In my app, I'm using a switch and changing the tint color to differentiate ON and OFF, but my actual requirement is to show "YES" or "NO" text inside the switch like below. Here is my Code: <Switch onValueChange={this.change.bind(this)} style={{marginBottom:10,width:90,marginRight:6,marginLeft:6}} value={true} thumbTintColor="#0000ff" tintColor="#ff0000" /> Please give me suggestions to solve this issue, Any help much appreciated.
Finally I got the On off inside switch ....... install npm install --save react-native-switch import { Switch } from 'react-native-switch'; <Switch value={true} onValueChange={(val) => console.log(val)} disabled={false} activeText={'On'} inActiveText={'Off'} backgroundActive={'green'} backgroundInactive={'gray'} circleActiveColor={'#30a566'} circleInActiveColor={'#000000'}/> Refer this link... https://github.com/shahen94/react-native-switch
I would start with something like this and then iterate and polish until it fulfills the requirements and looks good. This isn't a complete solution but should give you some ideas. import React from 'react'; import { LayoutAnimation, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; const styles = StyleSheet.create({ container: { width: 80, height: 30, backgroundColor: 'grey', flexDirection: 'row', overflow: 'visible', borderRadius: 15, shadowColor: 'black', shadowOpacity: 1.0, shadowOffset: { width: -2, height: 2, }, }, circle: { width: 34, height: 34, borderRadius: 17, backgroundColor: 'white', marginTop: -2, shadowColor: 'black', shadowOpacity: 1.0, shadowOffset: { width: 2, height: 2, }, }, activeContainer: { backgroundColor: 'blue', flexDirection: 'row-reverse', }, label: { alignSelf: 'center', backgroundColor: 'transparent', paddingHorizontal: 6, fontWeight: 'bold', }, }); class LabeledSwitch extends React.Component { constructor(props) { super(props); this.state = { value: props.value, }; this.toggle = this.toggle.bind(this); } componentWillReceiveProps(nextProps) { // update local state.value if props.value changes.... if (nextProps.value !== this.state.value) { this.setState({ value: nextProps.value }); } } toggle() { // define how we will use LayoutAnimation to give smooth transition between state change LayoutAnimation.configureNext(LayoutAnimation.Presets.spring); const newValue = !this.state.value; this.setState({ value: newValue, }); // fire function if exists if (typeof this.props.onValueChange === 'function') { this.props.onValueChange(newValue); } } render() { const { value } = this.state; return ( <TouchableOpacity onPress={this.toggle}> <View style={[ styles.container, value && styles.activeContainer]} > <View style={styles.circle} /> <Text style={styles.label}> { value ? 'YES' : 'NO' } </Text> </View> </TouchableOpacity> ); } } LabeledSwitch.propTypes = { onValueChange: React.PropTypes.func, value: React.PropTypes.bool, }; LabeledSwitch.defaultProps = { }; export default LabeledSwitch;