I built my own button component and I can't get it to work

56 Views Asked by At

I built my own button component using React Native and I am trying to use it in my code. All I am trying to do for now is to get it to log a console message and for some reason it's not doing it.

Button Component

import React, {Component} from 'react';
import { Text, TouchableOpacity } from 'react-native';

class Button extends Component {
  render(){
    const { onPress, children } = this.props;
    const { buttonStyle, textStyle } = styles;

    return (
      <TouchableOpacity onPress={ onPress } style={ buttonStyle }>
        <Text style={ textStyle }>
          { children }
        </Text>
      </TouchableOpacity>
    );
  }
}

Code using the Button

class FlashcardMenuDetail extends Component {
  onButtonPress() {
    console.log('You pushed the button');
  }

  render() {
    const { title } = this.props.flashcard;

    return (
      <Card>
        <CardItem>
          <Button onpress={this.onButtonPress.bind(this)}>
            { title }
          </Button>
        </CardItem>
      </Card>
    );
  }
}

I can push the button but nothing shows up on the console window.

1

There are 1 best solutions below

0
On

There is no arrow function in the button you made onPress When the function of the function is used, only the console log is left because the return value is imported. You have to add an arrow function.

export const makeButton = (props) => {
    const { title = "title", buttonStyle = {}, textStyle = {}, onPress } = props;

    return (
        <TouchableOpacity onPress={() => onPress} style={buttonStyle}>
            <Text style={textStyle}>{props.title}</Text>
        </TouchableOpacity>
    );
};

Usage

import { makeButton } from 'path/makeButton.js';


      <Card>
        <CardItem>
         <makeButton
            title="get console.log"
            onPress={() => onButtonPress() }
            buttonStyle ={{ /* some styles for button */ }}
            textStyle={{ /* styles for button title */ }}
        />
        </CardItem>
      </Card>