How to use this.state with react-native? - react-native

Hi I'm new to react so bear with me.
Below is my code...
import React from 'react';
import { StyleSheet, Text, View, TouchableHighlight, AsyncStorage} from 'react-native';
export default class App extends React.Component {
constructor(){
super();
this.state = {
myLeader: 'Joe',
};
}
onPress(){
alert({this.state.myLeader}); // 14
}
render() {
return (
<View>
<TouchableHighlight onPress={this.onPress.bind(this)}>
<Text>{this.state.myLeader}</Text>
</TouchableHighlight>
</View>
);
}
}
How to fix this problem?
error message is this. 'this is a reserved word(14.9) at Home.js:14.9'
I want to use {this.state.myLeader} in
onPress(){
alert({this.state.myLeader});
}
I tried 'bind(this)'
Any clue why?

Be careful with your usage of {}. In the context of JSX, {} can be used to "interpolate" a value within it. But if you're writing plain JavaScript code (as in alert({this.state.myLeader})) you don't need to interpolate anything, you just pass the value this.state.myLeader to alert, as in alert(this.state.myLeader).
Regarding the usage of alert within React Native, you'll probably want to follow #kytwb's advise and use Alert.alert.

Try to replace line 14 with:
console.log(this.state.myLeader)
To use Alert with React Native, take a look at the doc.

First, import Alert from react-native:
import { StyleSheet, Alert, Text, View, TouchableHighlight, AsyncStorage} from 'react-native';
Then, change the onPress function:
onPress(){
Alert.alert(this.state.myLeader); // 14
}

Another solution is to forget about the bind and do this:
onPress = () => {
alert({this.state.myLeader}); // 14
}
<TouchableHighlight onPress={this.onPress}>

Related

React-native QR code scanner is throwing error

I have a react-native app where I have developed a scanner feature using react-native-qrcode-scanner.However, when I try to scan the data, I get the below error-
error: can't find variable navigation
I see this error in onSuccess method at line authorizationToken.
My code-
import React, { Component } from 'react';
import {
Text,
View,
Image,
TouchableOpacity,
Linking
} from 'react-native';
import styles from '../assets/style';
import QRCodeScanner from 'react-native-qrcode-scanner';
export default class ScanScreen extends Component {
onSuccess(scanEvent) {
this.props.navigation.navigate("Result", {
'accessKey': scanEvent.data,
'authorizationToken':navigation.getParam('authorizationToken', undefined),
"userData": navigation.getParam('userData', undefined),
"methodName": "fetchData"
});
}
render() {
return (
<View style={styles.container}>
<QRCodeScanner
onRead={this.onSuccess.bind(this)}
/>
</View>
);
}
}
Any idea what I m missing here. Any help is much appreciated.Thanks in advance.
Make sure that Your Screen is registered in react-navigation config (follow this guide: can't find variable navigation).
Or pass navigation prop to it with HOC withNavigation: https://reactnavigation.org/docs/en/with-navigation.html. Instead export default class ScanScreen extends Component do class ScanScreen extends Component and at end of file do
export default withNavigation(ScanScreen);
Don't forget about importing Higher Order Component: import { withNavigation } from 'react-navigation';
Also be sure that all native parts are properly linked. For example react-native-gesture-handle (https://kmagiera.github.io/react-native-gesture-handler/docs/getting-started.html#linking).
navigation has to be part of props so accessing navigation using this.props.navigation solves this issue.

React-native Animating Circular progress not work properly

I want to draw a animated circuler progress on which run with duration when i start animation it show not properly After Complete Animation it show only a
import { AnimatedCircularProgress } from 'react-native-circular-progress';
import React,{Component} from 'react';
import PercentageCircle from 'react-native-percentage-circle';
import {
AppRegistry,
Image,
StatusBar,
StyleSheet,
TouchableOpacity,
View,
} from 'react-native';
export default class FirstScreen extends Component {
componentDidMount() {
this.circularProgress.performLinearAnimation(100, 8000);
}
render() {
return (
<View>
<AnimatedCircularProgress
size={120}
width={15}
fill={100}
tintColor="#00e0ff"
backgroundColor="#3d5875"
ref={(AnimatedCircularProgress) => { this.circularProgress = AnimatedCircularProgress; }}/>
</View>
);
}
}
AppRegistry.registerComponent('GTproject', () =>FirstScreen);
The link i follow is https://github.com/bgryszko/react-native-circular-progress
The Screen shot of animation from start to end first it start a circle from 0 but one line from an other side is also with this circle as in show below link
First it show as https://ibb.co/kEZ2za
Then it show as
https://pictub.club/image/79MtJC
Then after complete circle it show only line
https://pictub.club/image/79M9WG
This sounds like this bug encountered with recent React Native versions on Android: https://github.com/bgryszko/react-native-circular-progress/issues/64
It's fixed in this fork: https://github.com/andreiciceu/react-native-circular-progress

Whats wrong, my app always stuck at AwesomeProject welcome page

So i am stuck in there. I just want to add a but it never renders it.
It renders the "Registered project page".
index.ios.js
import native from './src';
native();
./src/index.js
import { AppRegistry, Text } from 'react-native';
import React, { Component } from 'react';
export default function index() {
class Root extends Component {
render() {
return (
<Text>
Welcome to React Native!
</Text>
);
}
}
AppRegistry.registerComponent('AwesomeProject', () => Root);
}
So it all works great. I can even debug and see that the App component is called etc. But why i never get to render anything except that window ?

What is the recommended way to apply styles to an extended React Native component?

I have extended the Text component in order to have a reusable text component with a custom font.
My custom component should accept the styles passed to it and add the custom font to it.
I'm currently doing this:
MyText.js
import React from 'react'
import {
Text,
StyleSheet
} from 'react-native';
export default class MyText extends React.Component {
render() {
const style =
Object.assign( {},
StyleSheet.flatten(this.props.style),
{fontFamily: "My Font"}
);
return (
<Text style={style}>
{this.props.children}
</Text>
);
}
}
While this works as expected, having to flatten the stylesheet every time seems wrong. The above is a trivial example, and I can think of other components on which I could use this pattern. For that reason, I want to make sure I'm not ignoring a more suitable approach.
Well it depends on how much you would want to customize. In this case , if it is just a different font, it could be something like
import React from 'react'
import {
Text,
StyleSheet
} from 'react-native';
import _ from 'lodash';
export default class MyText extends React.Component {
render() {
const filteredProps = _.omit(this.props, 'style');
return (
<Text style={[{fontFamily: "My Font"}, this.props.style]} {...filteredProps} />
);
}
}

React native, passing variables from other files

I am new to react native and I am having trouble passing variables from one file to another.
module.exports works great when passing classes.
However is there any way in native to pass variables from file to file by exporting?
In the example below, one file (button) is creating an array of random numbers and I want to access that array in another file (genreSelector). Similarly I am trying to pass an array of strings from (genre to genreSelector).
I cant find an example of how to do this so I am under the impression that it isn't possible. How should I be passing information if this isn't possible?
Do I need to have all the functions in my main and call them from within the child classes, if so how do I reference the function of the parent class rather than its own this.function?
So main is rendered in index.android.js and it all works great. Bar of course the passing of arrays from file to file. I tried using states but still cant access the variables as desired.
Apologies for such a basic question asked in such a complicated way.
//this is button.js
import React, { Component } from 'react';
import {
Alert,
AppRegistry,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import styles from '../styles/styles.js';
let rNumbers = [1,2,3];
var Button = React.createClass({
rNumberGen: function(){
let rNumbers = [Math.random(), Math.random(), Math.random()];
},
render: function(){
return(
<TouchableHighlight onPress={this.rNumberGen} style={styles.center}>
<Text style={styles.button}>Generate!</Text>
</TouchableHighlight>
);
}
});
module.exports = rNumbers;
module.exports = Button;
//this is genreSelector
import React, { Component } from 'react';
import {
Alert,
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import{
genre1,
genre2,
genre3
} from './genres.js';
import rNumbers from './button.js';
import styles from '../styles/styles.js';
let a = rNumbers.toString();
Alert.alert('This is', a);
var Genre = React.createClass({
render: function(){
let genre = this.props.selected;
return(
<View style={styles.genre}>
<Text style={styles.center}>{genre}</Text>
</View>
);
}
});
module.exports = Genre;
//This is main.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import
Button
from './button.js';
import
Genre
// genres
from './genreSelector.js';
import
styles
from '../styles/styles.js';
class Main extends React.Component {
render(){
return(
<View style={styles.container}>
<Text style={styles.title}>Genre Genrerator</Text>
<Text style={[styles.h2, styles.h21]}>I am listening to</Text>
<View style={styles.genreContainer}>
<Genre selected='{genres[1]}'/>
<Genre selected='{genres[2]}'/>
<Genre selected='{genres[3]}'/>
</View>
<Text style={styles.h2}>You filthy casual</Text>
<Button/>
</View>
);
}
}
module.exports = Main;
module.exports = rNumbers;
module.exports = Button;
You are overwriting it by assigning like that. You should use export keyword:
export {rNumbers};
export {Button};
then import like so:
import {rNumbers} from './button.js';
import {Button} from './button.js';
edit: error: expected { after export. Added in