React-Native Constructor - react-native

Please help me find what is wrong in the following React-Native code?
It says after constructor (props) should have ';' semicolon. I don't know if I declared it in the right way.
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default function App() {
constructor (props){
this.state = {
text: 'HI'
}
}
render () {
return (
<View style={styles.container}>
<TextInput style={styles.input}
placeholder = 'Enter Value...'
placeholderTextColor ='#E74292'
onChangeText = {(text) => {
this.setState({text})
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container:{
flex:1,
backgroundColor:'#F4C724',
},
input :{
marginTop:30,
height:30,
width:30,
borderWidth:2,
padding:10,
borderRadius: 5,
borderColor:'#1287A5'
}
}
);

You should declare the component as class instead of function if you want a constructor:
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default class App {
constructor(props) {
this.state = {
text: 'HI'
};
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Enter Value..."
placeholderTextColor="#E74292"
onChangeText={text => {
this.setState({ text });
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F4C724'
},
input: {
marginTop: 30,
height: 30,
width: 30,
borderWidth: 2,
padding: 10,
borderRadius: 5,
borderColor: '#1287A5'
}
});

constructor only works in class based component so switch to class based component rather than . functional whihc is now.
import React from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
export default class App extends React.Component{
constructor(props) {
this.state = {
text: 'HI'
};
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Enter Value..."
placeholderTextColor="#E74292"
onChangeText={text => {
this.setState({ text });
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F4C724'
},
input: {
marginTop: 30,
height: 30,
width: 30,
borderWidth: 2,
padding: 10,
borderRadius: 5,
borderColor: '#1287A5'
}
});

You need to study the difference between functional and class component.
Functional component is just a plain java-script function which also known as stateless component. They do not manage their own state or have access to the lifecycle methods.
for more please follow the link below:
https://medium.com/#Zwenza/functional-vs-class-components-in-react-231e3fbd7108

you can use useState , the dynamic function value loads to the initial variable on load
import React,{ useState } from 'react';
import { View, Text, Button, ImageBackground} from 'react-native';
export default function Home({navigation}){
//function getversion onload
const [initval,setInitval] = useState(()=>{ return '123456'});
return(
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text> {initval} </Text>
</View>
);
}

You cannot have a constructor() in functional components. You should either change function component to class component or go and check out the react doc about React Hooks. You are going to have a better understanding of the differences between react class components and react functional components.

Related

Invalide hook call, Hooks can only be calle inside of the body of a function component

i created a functionnal component
import React from 'react';
import { View, ScrollView, Text, SafeAreaView } from 'react-native';
import { useState, useEffect } from 'react';
const listFiliere = ({item}) => {
const [show, setShow] = useState(false);
return(
<View style={{ height: 30, flex: 1, justifyContent: 'center', borderBottomWidth: 1, borderBottomColor: 'blue' }}>
<Text>{ item.name }</Text>
</View>
);
}
export default listFiliere
I called this one inside class component for renderItem of flatlist; and it return error of invlide hook call; Is the class component which called it the cause or anything else?
it could be a few things. the code you posted is not a lot to go on. Take a look at this page. A few things you can check
If the problem is that you are calling useState in a class component, please reference this post.
Basically, you cannot use the useState hook in a class component. The class component equivalent would be:
export class ListFiliere extends React.Component {
constructor(props) {
super(props);
this.state = {
show: false
};
}
render() {
return(
<View style={{ height: 30, flex: 1, justifyContent: 'center', borderBottomWidth: 1, borderBottomColor: 'blue' }}>
<Text>{ item.name }</Text>
</View>
);
}
}

Error: Element type is invalid: expected a string (for build-in components) or a class/function... - REACT NATIVE

I got this error while working on my Content.js file:
Before this everything was fine so I know it's not App.js or another file.
I've tried 'npm install' just in case... Most people online that experienced similar errors mention that it might have to do with the way the component is exported but I already changed it to 'export default class Content extends Component' just like most people suggested.
This is the file:
Content.js
import React, { Component } from "react";
import { StyleSheet, View, ActivityIndicator, ScrollView, Card, Text} from 'react-native';
import firebase from '../../firebase';
export default class Content extends Component {
constructor() {
super();
this.state = {
isLoading: true,
article: {},
key: ''
};
}
componentDidMount() {
const ref = firebase.firestore().collection('articles').doc('foo');
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
article: doc.data(),
key: doc.id,
isLoading: false
});
} else {
console.log("No such document!");
}
});
}
render() {
if(this.state.isLoading){
return(
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
)
}
return (
<ScrollView>
<Card style={styles.container}>
<View style={styles.subContainer}>
<View>
<Text h3>{this.state.article.title}</Text>
</View>
<View>
<Text h5>{this.state.article.content}</Text>
</View>
</View>
</Card>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20
},
subContainer: {
flex: 1,
paddingBottom: 20,
borderBottomWidth: 2,
borderBottomColor: '#CCCCCC',
},
activity: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
})
You have imported Card from the react-native but React native does not provide Card component inbuilt.

How to write Custom flash message in react native

I want to display a custom message after successful record update when boolean value of recordUpdateSuccess become true and after 3seconds it should disappear.
{recordUpdateSuccess ? this.renderRecordUpdatedSucess() : null}
I have function to display message:
renderRecordUpdatedSucess = () => (
<View style={styles.sucessAlert}>
<Text style={styles.sucessAlert}>Record updated successfully.</Text>
</View>
)
I tried to use setTimeout() to display message but not working.
Any idea to acheive this one.
I don't want to use Toast, any third party library for this one.
Custom flash message (No external Library)
Working Example: https://snack.expo.io/#msbot01/1dcddc
import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
flashMessage: false
}
}
onPress(){
this.setState({
flashMessage: true
},()=>{setTimeout(() => this.closeFlashMessage(), 3000)})
}
closeFlashMessage(){
this.setState({
flashMessage: false
})
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={()=>{this.onPress()}}>
<Text>Click Me</Text>
</TouchableOpacity >
{this.state.flashMessage==true?
<View style={styles.flashMessage}>
<Text style={{color:'white'}}>This is custom Flash message</Text>
</View>
:
null
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
flashMessage:{
position:'absolute',
backgroundColor:'green',
width:'100%',
justifyContent:'center',
alignItems:'center',
height:40,
top:0
}
});

How to set default props values to custom state less component in React Native

I have a really simple component, called Divider here is the source code:
import React from "react";
import { StyleSheet, View } from "react-native";
export default class Divider extends React.Component {
render() {
return (
<View style = { styles.separator } />
);
}
}
const styles = StyleSheet.create({
separator: {
height: StyleSheet.hairlineWidth,
marginBottom: 8,
backgroundColor: "#FFFFFF80",
},
});
What I am trying to achieve is that the values in styles.separator becomes the default values of this component, since those are the values which I am using in most cases, but in some edge cases I need to change the marginBottom to 16 for example.
So most case I just want to do <Divider />, but sometimes <Divider marginBottom = 16 />
What I have currently is something like this below, but obviously this doesn't work.
import React from "react";
import { StyleSheet, View } from "react-native";
export default class Divider extends React.Component {
static defaultPropts = {
marginTop: 0,
marginBottom: 8,
backgroundColor: "#FFFFFF80",
}
render() {
return (
<View style = {{
height: StyleSheet.hairlineWidth,
marginTop: {this.props.marginTop},
marginBottom: {this.props.marginBottom},
backgroundColor: {this.props.backgroundColor},
}} />
);
}
}
You can receive your custom style by props and use them in your component style as array. When you call the props style after the component's, it will overwrite any equal style property it already has.
For example, let's say you have a component named 'Card', you can write your component like this:
<View style={[style.cardStyle, props.style]}>
{props.children}
</View>
And call it like this <Card style={{ backgroundColor: '#FFFFFF'}} />
So it's getting all defined 'cardStyle' from it's own component, also adding the styles received by props.
Hope it helps.
EDIT:
You can try something like this
import React from "react";
import { StyleSheet, View } from "react-native";
const Divider = (props) => {
<View style = {{
height: StyleSheet.hairlineWidth,
marginTop: {this.props.marginTop},
marginBottom: {this.props.marginBottom},
backgroundColor: {this.props.backgroundColor},
}} />
}
Divider.defaultProps = {
marginTop: 0,
marginBottom: 8,
backgroundColor: "#FFFFFF80",
}
export default Divider;
Let me know if it works for you.
you can do like this
export default class Divider extends React.Component {
render() {
return (
<View style = {{
height: StyleSheet.hairlineWidth,
marginTop: {this.props.marginTop},
marginBottom: {this.props.marginBottom},
backgroundColor: {this.props.backgroundColor},
}} />
);
}
}
Divider.defaultProps = {
marginTop: 0,
marginBottom: 8,
backgroundColor: "#FFFFFF80",
}
So after researching a bit I found out that this works.
import React from "react";
import { Dimensions, StyleSheet, View } from "react-native";
export default class Divider extends React.Component {
static defaultProps = {
customWidth: Dimensions.get("window").width / 2.0,
}
render() {
const halfWidth = this.props.customWidth
return (
<View style = { [styles.separator, {width: halfWidth}] } />
);
}
}
const styles = StyleSheet.create({
separator: {
height: StyleSheet.hairlineWidth,
backgroundColor: "#FFFFFF80",
},
});
So now whenever I use <Divider /> its width gonna be half of the screen size, but if I dod <Divider customWidth = { 10 }, then it will overwrite the default value and will be 10 dp instead.

React Native render and switch with navigator onPress

I've just started to develop with React Native a week ago.
Can anyone help me with simple render and switch onPress to another view?
I've read tones of examples, but most of them are cutted or not well documents as if on FaceBook Doc pages. There was no totally completed example with Nav.
Here is what was done yet - View that should be rendered 1st:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TextInput,
TouchableHighlight,
TouchableNativeFeedback,
Platform,
Navigator
} from 'react-native';
export default class SignUp extends Component {
buttonClicked() {
console.log('Hi');
this.props.navigator.push({title: 'SignUp', component:SignUp});
}
render() {
var TouchableElement = TouchableHighlight;
if (Platform.OS === ANDROID_PLATFORM) {
TouchableElement = TouchableNativeFeedback;
}
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to Cross-Profi!
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} placeholder="Profession" />
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} placeholder="E-mail" />
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} secureTextEntry={true} placeholder="Password" />
</Text>
<TouchableElement style={styles.button} onPress={this.buttonClicked.bind(this)}>
<View>
<Text style={styles.buttonText}>Register</Text>
</View>
</TouchableElement>
{/* <Image source={require("./img/super_car.png")} style={{width:120,height:100}} />*/}
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'lightblue',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: 'darkred',
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
field_row: {
textAlign: 'center',
color: '#999999',
margin: 3,
},
stdfield: {
backgroundColor: 'darkgray',
height: 50,
width: 220,
textAlign: 'center'
},
button: {
borderColor:'blue',
borderWidth: 2,
margin: 5
},
buttonText: {
fontSize: 18,
fontWeight: 'bold'
}
});
const ANDROID_PLATFORM = 'android';
Navigator class that should render different views:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Platform,
Navigator
} from 'react-native';
var MainActivity = require('./app/MainActivity.js');
var SignUp = require('./app/SignUp.js');
class AwesomeProject extends Component {
/*constructor(props) {
super(props);
this.state = {text: ''};
}*/
render() {
// this.props.navigator.push({title:'SignUp'});
return (
<Navigator initialRoute={{title:'SignUp', component:SignUp}}
configureScene={() => {
return Navigator.SceneConfigs.FloatFromRight;
}}
renderScene={(route, navigator) =>
{
console.log(route, navigator);
if (route.component) {
return React.createElement(route.component, {navigator});
}
}
} />
);
}
}
const ANDROID_PLATFORM = 'android';
const routes = [
{title: 'MainActivity', component: MainActivity},
{title: 'SignUp', component: SignUp},
];
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
It doesn't seem to be clear whether there must be require of a class and declaration of class as export default.
There is an error: Element type is invalid: expected a string, ... but got object etc
Help with examples would be great. Thx
In your require call, you should either replace it import statement or use default property of require module i.e:
var MainActivity = require('./app/MainActivity.js').default;
or use
import MainActivity from "./app/MainActivity";
In ES6, require doesn't assign default property of module to variable.
See this blog post for better understanding of require working in es6