s4inz
s4inz

Reputation: 123

Modify state by pressing a button in react native

I'm still doing my first steps in react native development for Android & iOS and I stumbled across a (supposedly simple) problem with buttons. I do not know how to modify a text field by pressing a button.

I tried using states, so this is how it currently looks like:

import React, { Component } from 'react';
import {
  ...
  Button
} from 'react-native';

// more code

class ExampleButton extends ParseComponent {
   constructor() {
      super();
      this.state = {
         label: 'nothing'
      }
}

// more code

render() {
   if(...) {
      return (
         <Button
           onPress={onButtonPress}
           title="Click_test"
           color="#841584"/>
       );
   }
}

const onButtonPress = () => { this.setState({label: 'something' });

However, I get an error message on pressing the button that says

... unexpected token, expected (....

in line const onButtonPress......

I'd be very about any hint! :) Thank you.

Upvotes: 0

Views: 293

Answers (1)

Matt Aft
Matt Aft

Reputation: 8936

class ExampleButton extends ParseComponent {
   constructor() {
     super();
     this.state = {
       label: 'nothing'
     }
   }

// more code
onButtonPress = () => { //Make a property of ExampleButton class
  this.setState({label: 'something' });
} //was missing this closing bracket

render() {
   if(...) {
      return (
         <Button
           onPress={this.onButtonPress} //change to this.onButtonPress
           title="Click_test"
           color="#841584"/>
       );
   }
}

Upvotes: 1

Related Questions