React Nat Counter - javascript

When clicking on a button, I want a value to increment by one each time. I want to call a function incrementCounter() to handle the operation for me, rather than: onPress={() => this.setState({Count: ++this.state.Count})}
This is my code so far for the class:
class Main extends React.Component{
constructor(props){
super(props);
this.state = {
Count: 0,
}
}
incrementCounter(){
this.setState({
Count: this.state.Count + 1 //!!! Where error occurs
});
}
render() {
return(
<View style={styles.mainContainer}>
<Text style={styles.title}>{'Count: ' + this.state.Count} </Text>
<TouchableHighlight
style={styles.button}
onPress={this.incrementCounter}
underlayColor='white'>
<Text style={styles.buttonText}>+</Text>
</TouchableHighlight>
</View>
)
}
};
The code above results in an error - a red screen:
"undefined is not an object (evaluating 'this.state.Count')" with the error on the line of the incrementCounter() <- Where comments show error occurs.
Most of the examples that I can find online are not using the ES6 syntax, however I want to try and stick to this to keep it standard across my application. The future work will include having a decrementCounter() function that will do the opposite, however will not allow the counter to drop below zero.

I see you are using the es6 notation, try the following:
render() {
return(
<View style={styles.mainContainer}>
<Text style={styles.title}>{'Count: ' + this.state.Count} </Text>
<TouchableHighlight
style={styles.button}
onPress={this.incrementCounter.bind(this)}
underlayColor='white'>
<Text style={styles.buttonText}>+</Text>
</TouchableHighlight>
</View>
)
}
Notice the .bind(this) on the event, this is needed so that it acutally references the class itself not some global function.

Related

Natigate to different screes within same page in React Native

I have made a main screen in which I have added three button in the header, on pressing I want to open three different screens respectively but its not working.
Here's what I've tried:
constructor(props) {
super(props);
this.state = {
initialstate: 0, //Setting initial state for screens
};
}
render(){
return(
<View style={styles.container}>
<TouchableOpacity onPress={() => this.setState({ initialstate: 0})}>
<Image source={require('../../assets/add.png')}
resizeMode="contain"/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.setState({ cardstate: 1})}>
<Image source={require('../../assets/request.png')}
resizeMode="contain"/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.setState({ cardstate: 2})}>
<Image source={require('../../assets/send.png')}
resizeMode="contain"/>
</TouchableOpacity>
{this.state.initialstate == 0 ? ( <RequestComp/> ) : ( <TopUpComp/> ) } //Over Here when I use the Third Screen like " : <SendComp/> " it gives me JXS error says "EXPECTED }"
</View>
The first problem is that you have an initialState state variable that is only updated by the first buttons and the other two are setting cardState so even if the ternary statement was formatted correctly it wouldn't have worked either way
But aside from this problem I don't recommend using a ternary for what you're trying to do, because the conditions become difficult to read.
There are multiple ways of doing this, but I like the approach of the accepted answer here React render various components based on three logic paths). The idea is to create an object that holds a mapping of strings to components. Then you can conditionally render an item based on the current key value.
Here's an example of how you could refactor your code to use this approach:
const tabComponents = {
request: <RequestComp />,
topUp: <TopUpComp />,
send: <SendComp />,
};
class CustomTabs extends React.Component {
constructor(props) {
super(props);
this.state = {
cardstate: 'request', // Setting initial state for screens
};
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
onPress={() => this.setState({ cardstate: 'request' })}>
// Button content...
</TouchableOpacity>
<TouchableOpacity onPress={() => this.setState({ cardstate: 'topUp' })}>
// Button content...
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.setState({ cardstate: 'send' })}>
// Button content...
</TouchableOpacity>
{tabComponents[this.state.cardstate]}
</View>
);
}
}

React-Native Button On Press doesn't work

I can't bind my onPress method to my JSX button.
I've tried already tons of different solutions but none of them worked.
onPress Method:
class ScreenEnterPlayerNames extends Component {
constructor(props) {
super(props);
}
static navigationOptions = {
title: 'Player Names',
};
onPressStartTheGame = () => {
console.log("Pushed button Start the Game!")
//dispatch({ type: ADD_PLAYER_NAME, playerNumber: 5, playerName: "Sandro" })
}
Button:
return (
<View style={styles.viewMain}>
<View style={styles.viewTxt}>
<Text style={styles.TxtHeading}>
Please enter the names in sequence.
</Text>
</View>
<ScrollView style={styles.viewTextBox}>
{textBoxes}
</ScrollView>
<View style={styles.viewButton}>
<Button
title='Start the Game!'
onPress={() => this.onPressStartTheGame}
/>
</View>
</View>
);
}
}
I've tried it with following approaches as well:
onPress={this.onPressStartTheGame}
onPress={this.onPressStartTheGame()}
onPress={this.onPressStartTheGame.bind(this)}
onPress={() => this.onPressStartTheGame.bind(this)}
And I tried to change the function to:
onPressStartTheGame() {...
So I am pretty sure there is something else wrong but I can't figure out what.
Thank you! :-)
Try this for your method
onPressStartTheGame(){
console.log("Pushed button Start the Game!")
//dispatch({ type: ADD_PLAYER_NAME, playerNumber: 5, playerName: "Sandro" })
}
and call it like
onPress={this.onPressStartTheGame.bind(this)}
here you can double check and try the behave in a sandbox.
https://facebook.github.io/react-native/docs/handling-touches.html

How to move an Image on click in React Native

I've recently been learning React Native but haven't really found a way to manipulate the DOM.
I've been trying to make it so that if I click on the TouchableHighlight my Image moves down a couple of px, but I have not managed to get it to move yet and I honestly don't know how to go from here.
My onclick function works since it does return the log every time the button is clicked.
As of now I have this:
export default class MainBody extends Component {
onclick = () => {
console.log('On click works')
};
render() {
return (
<ScrollView showsHorizontalScrollIndicator={false} style={Style.horList} horizontal={true}>
<View >
{/*i need to move this Image down!*/}
<Image source={require("./img/example.png")}/>
<View>
<Text style={Style.peopleInvited}>This is text</Text>
</View>
{/*When clicked on this touchable highlight!*/}
<TouchableHighlight onPress={this.onclick}}>
<Image source={require('./img/moveImg.png')}/>
</TouchableHighlight>
</View>
</ScrollView>
}
If someone could help me get past this that would be greatly appreciated.
Thank you so much for your time!
There are many ways to do this, but perhaps the easiest way would be using states.
class MainBody extends Component {
constructor(props) {
super(props);
this.state = {
top: 0 // Initial value
};
}
onclick = () => {
console.log('On click works')
this.setState( { top: this.state.top + 5 }) // 5 is value of change.
};
render() {
return (
<ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>
<View >
{/*i need to move this Image down!*/}
<Image style={{top: this.state.top}}source={require("./img/example.png")}/>
<View>
<Text>This is text</Text>
</View>
{/*When clicked on this touchable highlight!*/}
<TouchableHighlight onPress={this.onclick}>
<Image source={require("./img/moveImg.png")}/>
</TouchableHighlight>
</View>
</ScrollView>
);
}
}

Undefined is not an object evaluating this.state/this.props

How do I bind a function outside of scope in React Native? I'm getting the errors:
undefined is not an object evaluating this.state
&
undefined is not an object evaluating this.props
I'm using the render method to evoke renderGPSDataFromServer() when the data has been loaded. The problem is, I'm trying to use _buttonPress() and calcRow() inside of renderGPSDataFromServer(), but I'm getting those errors.
I've added
constructor(props) {
super(props);
this._buttonPress = this._buttonPress.bind(this);
this.calcRow = this.calcRow.bind(this);
to my constructor and I've changed _buttonPress() { to _buttonPress = () => { and still nothing.
I think I understand the problem but I don't know how to fix it:
renderLoadingView() {
return (
<View style={[styles.cardContainer, styles.loading]}>
<Text style={styles.restData}>
Loading ...
</Text>
</View>
)
}
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map(function(data, i){
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
render = ()=> {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return(
<View>
{this.renderGPSDataFromServer()}
</View>
)
}};
How do I go about fixing this and in this case what is the problem?
this.props are read-only
React docs - component and props
And therefore a component shouldn't try a to modify them let alone mutate them as you are doing here:
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
I'd suggest using state instead:
_buttonPress = () => {
this.setState = {
...this.state,
navigator: {
...this.state.navigator,
id: 'Main'
}
}
}
Regarding your binding issue:
the .map method takes a 2nd argument that is used to set the value of this when the callback is invoked.
In the context of your question, you just need to pass thisas the 2nd argument to you .map method to bind the components scope's this to it.
This is happening because, the function inside the map method creates a different context. You can use arrow functions as the callback in the map method for lexical binding. That should solve the issue you are having.
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map((data, i) => {
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
Also, once you've used arrow functions in the class function definition you
don't need to bind them in constructor like:
constructor(props) {
super(props);
this._customMethodDefinedUsingFatArrow = this._customMethodDefinedUsingFatArrow.bind(this)
}
Also, once you have defined class functions as arrow functions, you
don't need to use the arrow functions while calling them either:
class Example extends React.Component {
myfunc = () => {
this.nextFunc()
}
nextFunc = () => {
console.log('hello hello')
}
render() {
// this will give you the desired result
return (
<TouchableOpacity onPress={this.myFunc} />
)
// you don't need to do this
return (
<TouchableOpacity onPress={() => this.myFunc()} />
)
}
}
not sure if this is the problem, but I think is code is wrong, and may be potentially causing your issue.
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress().bind(this)}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
specifically this line onPress={this._buttonPress().bind(this)}>
you are invoking the function and binding it at the same time.
The correct way to do this would be so
onPress={this._buttonPress.bind(this)}>
this way the function will be called only onPress.
You are going in the right direction, but there is still a minor issue. You are passing a function to your map callback that has a different scope (this) than your component (because it is not an arrow function), so when you do bind(this), you are rebinding your callback to use the scope from map. I think this should work, it basically turns the callback that you pass to map into an arrow function. Also, since you bind your function in the constructor, you do not need to do it again:
// The constructor logic remains the same
// ....
renderLoadingView() {
return (
<View style={[styles.cardContainer, styles.loading]}>
<Text style={styles.restData}>
Loading ...
</Text>
</View>
)
}
_buttonPress = () => {
this.props.navigator.push({
id: 'Main'
})
}
renderGPSDataFromServer =() => {
const {loaded} = this.state;
const {state} = this.state;
return this.state.dataArr.map((data, i) => {
return(
<View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}>
<View style={styles.cardContentLeft}>
<TouchableHighlight style={styles.button}
onPress={this._buttonPress}>
<Text style={styles.restData}>View Video</Text>
</TouchableHighlight>
</View>
<View style={styles.cardContentRight}>
<Text style={styles.restData}>{i}</Text>
<View style={styles.gpsDataContainer}>
<Text style={styles.gpsData}>
{Number(data.lat).toFixed(2)}</Text>
<Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text>
</View>
<Text style={styles.gpsData}>
{this.calcRow(55,55).bind(this)}
</Text>
</View>
</View>
);
});
}
render = ()=> {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return(
<View>
{this.renderGPSDataFromServer()}
</View>
)
}};

React Native Change State With Unexpected Logging

For context, I am working on this React Native Tutorial
The way this logs confuses me. The following is the console output when I changed an empty input field by typing "a" then "b".
Here's my SearchPage class. Why does console.log('searchString = ' + this.state.searchString); show the previous value for this.state.searchString?
class SearchPage extends Component {
constructor(props) {
super(props);
this.state = {
searchString: 'london'
};
}
onSearchTextChanged(event) {
console.log('onSearchTextChanged');
console.log('searchString = ' + this.state.searchString +
'; input text = ' + event.nativeEvent.text );
this.setState({ searchString: event.nativeEvent.text });
console.log('Changed State');
console.log('searchString = ' + this.state.searchString);
}
render () {
console.log('SearchPage.render');
return (
<View style={styles.container}>
<Text style = { styles.description }>
Search for houses to Buy!
</Text>
<Text style = {styles.description}>
Search by place name or search near your location.
</Text>
<View style={styles.flowRight}>
<TextInput
style = {styles.searchInput}
value={this.state.searchString}
onChange={this.onSearchTextChanged.bind(this)}
placeholder='Search via name or postcode'/>
<TouchableHighlight style ={styles.button}
underlayColor = '#99d9f4'>
<Text style ={styles.buttonText}>Go</Text>
</TouchableHighlight>
</View>
<TouchableHighlight style={styles.button}
underlayColor= '#99d9f4'>
<Text style={styles.buttonText}>Location</Text>
</TouchableHighlight>
<Image source={require('image!house')} style={styles.image}/>
</View>
);
}
}
setState can be an asynchronous operation, not synchronous. This means that updates to state could be batched together and not done immediately in order to get a performance boost. If you really need to do something after state has been truly updated, there's a callback parameter:
this.setState({ searchString: event.nativeEvent.text }, function(newState) {
console.log('Changed State');
console.log('searchString = ' + this.state.searchString);
}.bind(this));
You can read more on setState in the documentation.
https://facebook.github.io/react/docs/component-api.html

Categories