Coder Social home page Coder Social logo

react-native-button's Introduction

react-native-button

A button for React apps

Usage

Install the button from npm with npm install react-native-button --save. Then, require it from your app's JavaScript files with import Button from 'react-native-button'.

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

export default class ExampleComponent extends Component {
  constructor(props, context) {
    super(props, context);
  }
  _handlePress() {
    console.log('Pressed!');
  }
  render() {
    return (
      <Button
        style={{fontSize: 20, color: 'green'}}
        styleDisabled={{color: 'red'}}
        onPress={() => this._handlePress()}>
        Press Me!
      </Button>
    );
  }
};

The React packager will include the Button component in your app's JS package and make it available for your app to use.

Disabled prop usage

You can control a button's state by setting disabled prop value in this way:

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

export default class ExampleComponent extends Component {
  constructor(props, context) {
    super(props, context);
      this.state = {
        isDisabled: false
      }
    }
  _handlePress() {
    this.setState({
      isDisabled: true
    });
    console.log('Now, button disabled');
  }
  render() {
    const { isDisabled } = this.state;
    return (
      <Button
        style={{ fontSize: 20, color: 'white' }}
        styleDisabled={{ color: 'white' }}
        disabled={isDisabled}
        containerStyle={{ padding: 10, height: 45, overflow: 'hidden', borderRadius: 4, backgroundColor: 'aqua' }}
        disabledContainerStyle={{ backgroundColor: 'pink' }}
        onPress={() => this._handlePress()}
      >
        Press Me!
      </Button>
    );
  }
};

Props

Prop Required Type Description
accessibilityLabel No String VoiceOver will read this string when a user selects the associated element.
allowFontScaling No Bool Specifies whether fonts should scale to respect Text Size accessibility settings.
Disabled No Bool Disables the button
Style No View Style Prop The style for the button
styleDisabled No View Style Prop The style for the disabled button
containerStyle No View Style Prop The style for the container
disabledContainerStyle No View Style Prop The style for the container when the button is disabled
childGroupStyle No View Style Prop The style for the child views
androidBackground No Background Prop Type The background for andriod devices.
onPress No Function Handler to be called when the user taps the button.

Container Style

You can make a button with rounded corners like this:

  <Button
    containerStyle={{padding:10, height:45, overflow:'hidden', borderRadius:4, backgroundColor: 'white'}}
    disabledContainerStyle={{backgroundColor: 'grey'}}
    style={{fontSize: 20, color: 'green'}}>
    Press me!
  </Button>

Contributing

Contributions are welcome. Please verify that styling matches the latest version of iOS when you are changing the visual look of the buttons.

react-native-button's People

Contributors

andrewljohnson avatar brentvatne avatar cooperka avatar drewmca avatar emersonlaurentino avatar enrique-money avatar evansolomon avatar haibinyu avatar ide avatar josenaves avatar karlosq avatar kdastan avatar maxcilauro avatar minelarka14 avatar nbolender avatar noktigula avatar peterlazar1993 avatar pyyoshi avatar tayzlor avatar vipansegrouw avatar wearenifty avatar zxcpoiu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-button's Issues

accessibilityLabel missing

I'm using this component in our app but have found that it does not uses accessibilityLabel.
I need to have accessibilityLabel set to my Appium end-to-end tests to work.

Unable to resolve module

I tried the instructions but when I import Button from 'react-native-button' red screen appears.

image

tried the instructions on the red screen, also looked at facebook/react-native#4968, but doesn't work.

Something is messed up and now I can't run any other projects on react-native. Running other projects gives me the same error message.

Any help?

Android style

The element in Android is not responding to the same style declarations as in iOS. In my case, I cannot seem to find a way to center the text inside of the button in Android.

Any thoughts on this?

Add `disable` usage to docs.

Currently there is no usage examples for disabled buttons. It would be helpful to have it available for ease of development.

How to add a image to the button

Thanks very much for creating this button. If i wanted to add a image to the button how might i do that?

I have attached a mock up of what i am looking for.

Eoin
screen shot 2016-07-13 at 14 41 25

onPress handler does not receive event

Hi there,

My onPress handlers are not receiving events - I'm using the buttons within a ListView:

var SettingsTab = React.createClass({
  getInitialState: function () {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      menuItems: ds.cloneWithRows(['Exercises']),
      menuRoutes: {
        Exercises: {
          title: ''
        }
      }
    }
  },
  _handleButtonPress: function (e) {
    console.log('e', e);
  },
  render: function () {
    return (
      <View style={{
        backgroundColor: '#414A8C',
        flex: 1,
        alignItems: 'center',
        paddingTop: 64
        }}>
        <ListView
          dataSource={this.state.menuItems}
          automaticallyAdjustContentInsets={false}
          renderRow={(rowData) => <Button onPress={this._handleButtonPress}>{rowData}</Button>}
          />
      </View>
    );
  }
});

In the above, e is undefined.

Any ideas?

Cheers!

Slow to respond on Android

The opacity just goes from 1 to 0.2 without an animation. I ran the button on a 5.1 Android device. On an emulator running Android 4.2 the animation is present but is choppy, like the framerate is low. This is my implementation:

import React, {Component} from 'react';
import {StyleSheet} from 'react-native';
import Button from 'react-native-button';
import Colors from '../resources/Colors.js';

/* STYLE */
const buttonStyle = StyleSheet.create({

    container: {
        margin: 20,
        padding: 10,
        height: 60,
        width: 60,
        borderRadius: 30,
        backgroundColor: Colors.primaryDark,
    },

});

/* WIDGET */
class RoundButton extends Component {

    constructor(props, context) {
        super(props, context);
    }

    //noinspection JSMethodCanBeStatic
    _handlePress() {
        // add functionality
        console.log("pressed");
    }

    render() {
        return (
            <Button
                containerStyle={buttonStyle.container}
                onPress={() => this._handlePress()}/>
        )
    }

}

module.exports = RoundButton;

Typescript support

Hey there, thanks for the lib!

I noticed there were no typings for this lib. I am new to Typescript so i can't really create them myself. I have started but I am not sure how to import the proptypes and extend from TouchableOpacity

If anyone can help that would be great

import { Component } from "react";

export = Button;

type ButtonProps = {
    allowFontScaling?: boolean;
    accessibilityLabel?: string;
    containerStyle?: object;
    disabledContainerStyle?: object;
    disabled?: boolean;
    style?: object;
    styleDisabled?: object;
    childGroupStyle?: object;
}

/*~ Write your module's methods and properties in this class */
declare class Button<P = {}, S = {}> extends Component<ButtonProps, S> {
    constructor(props: object);
}

Styling documentation

There isn't much documentation on how to style the View, Button, or Text. I'm therefore having to write my own button as such:

        <TouchableOpacity style={styles.buttonBg} onPress={this.onPress}>
          <Text style={styles.buttonText}>
            LOG IN
          </Text>
        </TouchableOpacity>

What is the purpose of _renderGroupedChildren?

What's the purpose of _renderGroupedChildren?

I'm trying to include an icon in a button, so it looks like:

    <Button style={{color: 'green'}} onPress={this._handlePress}>
      <View>
        <Text>Click Me</Text>
        <Icon name="rocket" />
      </View>
    </Button>

However, Button seems to only work if you include plain text without any children, like Icon or Text.

Buttons either don't style correctly or I'm doing something wrong.

Hello before I start, I am loving the concept/what you've done so far but have come across a bug/misunderstanding about how to style these buttons.

Below is some code I've written and the output is unexpected. essentially the spacing is broken and can't style them up to look like buttons.

screen shot 2015-05-05 at 20 39 13

var React = require('react-native');
var AuthActions = require('../actions/AuthActions.ios.js');
var UserService = require('../services/UserService.ios.js');
var Button = require('react-native-button');
var _ = require('lodash');

var {
  StyleSheet,
  TextInput,
  View,
  AlertIOS
} = React;

var LoginView = React.createClass({

  /** Stylesheet **/
  _styles: StyleSheet.create({
    viewContainer: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: '#000000'
    },
    buttonContainer: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
    },
    textBox: {
      fontSize: 20,
      textAlign: 'center',
      margin: 10,
      height: 40,
      borderRadius: 20,
      backgroundColor: '#FFFFFF',
      paddingLeft: 20
    }
  }),

  /** Login Action**/
  _handleLoginAction: function() {

    if(!_.isEmpty(this.state.email) && !_.isEmpty(this.state.password)) {

      UserService.authUser({
        email: this.state.email, 
        password: this.state.password 
      }, function(err, res){

        var response = JSON.parse(res.text);
        AuthActions.loggedIn(response.authCode);
      });

    } else {

      AlertIOS.alert(
        'Woops',
        'You have not provided all the information, please try again.'
      );
    }
  },
  getInitialState : function(){

    return {
      email: false, 
      password: false
    };
  },
  /** Lifecycle **/
  render: function() {
    return (
      <View style={this._styles.viewContainer}>
        <TextInput
          placeholder={'Email'}
          style={this._styles.textBox}
          onChangeText={(email) => this.setState({email: email})}
        />
        <TextInput
          placeholder={'Password'}
          style={this._styles.textBox}
          password={true}
          onChangeText={(password) => this.setState({password: password})}
        />
        <View style={this._styles.buttonContainer}>
          <Button style={{textAlign: 'left', flex: 1, color: 'green'}} onPress={this._handleLoginAction}>
            Register
          </Button>
          <Button style={{textAlign: 'left', flex: 1, color: 'green'}} onPress={this._handleLoginAction}>
            Login
          </Button>
        </View>
      </View>
    );
  }
});

module.exports = LoginView;

Ability to Pass ID or Argument

Would like to be able to pass an ID or argument to the button. For example if I do

 <Button ref="MyButton" onpress={this.buttonPressed}>Hi</Button>

I would like to be able to reference that "MyButton" was pressed allowing me to send to a single function when having multiple buttons on a screen.

[Android] Padding is cutting off the last word in a Button

Hey James, I came across this weird behavior when using your awesome component and I thought I'd report it here.

This component will behave perfectly fine

<Button>
  One Two Three
</Button>

This instead will cut the last word off, regardless of how many words are in the button and the amount of padding.

<Button style={{padding: 1}}>
  One Two Three
</Button>

The "raw" TouchableOpacity doesn't seem to be affected, since both these works fine:

<TouchableOpacity>
  <Text style={{padding: 4}}>One Two Three</Text>
</TouchableOpacity>

<TouchableOpacity style={{padding: 4}}>
  <Text>One Two Three</Text>
</TouchableOpacity>

Let me know if I can help!

1.7.0 cause app to throw an error

After the latest update my code leads to an error where it woks fine with 1.6.0. Error what i'm getting is,

Element type is invalid: expected a string (for build-in components) or a class/functions (for composite components) but got: object.

How to make a button that fills the parent container?

I need a button that fills the parent (basically the entire device screen) with some text in the center. I'm trying to do this with flexbox properties but since <Button> is evidently basically a <Text> element, it doesn't respond to flexbox. How would you suggest doing this (in a reasonably responsive way)?

Button: propType 'containerStyle' is invalid

Hi,
after upgrading from RN 0.17 to 0.19, I'm getting the following warning when using react-native-button:
Warning: Button: propType 'containerStyle' is invalid; it must be a function, usually from React.PropTypes.

The key prop needs to be added

Hello,
Great module!
I'd suggest you include the key prop since if you use your component inside a ListView or any other component that iterates through children, React will complain saying:
Warning: Each child in array or iterator should have a unique 'key' prop...

This would be solved if you change this:
<TouchableOpacity {...touchableProps} testID={this.props.testID} style={this.props.containerStyle}>
... with this:
<TouchableOpacity {...touchableProps} key={this.props.key} testID={this.props.testID} style={this.props.containerStyle}>

Alex

Should I still use this?

Hi James and other maintainers.
This button is awesome and serves me well in my projects. But the RN-world keeps spinning and there is now a Button component in RN core.

I prefer this button over the built in button. But I wonder if I should switch to a more modern button? I'm not using Expo (yet). @ide, What button component do you use in Expo?

the text is slightly above the center

Hi, I found the font HelveticaNeueInterface-MediumP4 would cause the issue with some languages, such as Japanese.
Now, my workaround is set the fontFamily to null in the style. it works okay though.

Center Text

I'm trying to center my Text perfectly centered inside the button. I've tried textAlign: 'center', and I can't seem to add padding on top. Seems like the text is being positioned to top of the container.

Usually lineHeight fixes this issue but in this case, not. :/

Long text within row

why they don't fit the screen ?

here is my styles :

answerContainer:{
    flex:0.2,
    width: WINDOW_WIDTH-10,
    flexDirection:'row',
    borderWidth: 1 / PixelRatio.get(),
    borderColor:'white',
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
    margin: 5,
  },
  button: {
    padding: 5,
    margin: 5,
    fontSize: 16,
    textAlign: 'center',
    color: 'white',
    backgroundColor: '#00C853',
    borderRadius: 10,
  },

simulator screen shot 24 oct 2015 02 46 10

Transparency on border radius not working

There is a white background no matter what, how do I remove this?

screen shot 2015-10-23 at 10 54 37 am

  button: {
    width: 300,
    height: 60,
    color: '#fff',
    backgroundColor: '#49A8A2',
    borderRadius: 20
  }

Button not applying disabledContainerStyle when disabled

Not applying disable styles, althouth the current code is correct when importing localy.
It appears the build is not is sync with the code

"react-intl-native": "2.1.0"
"react": "16.0.0-beta.5"
"react-native": "0.49.3"
Android API 23

Getting Error when using 2 button in one View

Hi there. I'm getting error rawtext "" must be wrapped in an explicit... each time i use 2 buttons inside 1 View.

I've tried to create components with button. I wrapped each button into a separate View and then used this component in a screen. Got same result!

Thanks.

how to set style radius of button

In simulator it's ok, but happed in device iphone 6 plus

screenshot like this
react-native-button

code

//jsx
 <Button style={styles.sendCode} onPress={this._sendCode}>
  {I18n.t('send_code')}
</Button>

// style

sendCode: {
    color: '#fff',
    borderRadius: 6,
    backgroundColor: '#F34A49',
    position: 'absolute',
    top: -10,
    right: 5,
    padding: 6,
    fontSize: 14
}

Border Width

Is it possible to add border to the button?
I was using native-base with a border, but this library is so much lighter, but I can't figure out how to add a border.

Provide numberOfLines prop for the text of the button

I want to be able to show ... if the text length is greater than available width which can be done by specifying numberOfLines property as 1 in the Text node but this property is currently not read in the Button component. I also tried to add it myself in the Button.js file but for some reason it didn't work. The property is not present on the Text node when I inspect it in the inspector but I have verified that the property was added in the code using the console logs. So, not sure why does it not appear in the rendered Text node.

Unexpected token

How can I patch this with my webpack config?

/node_modules/react-native-button/Button.js Line 18: Unexpected token ...
You may need an appropriate loader to handle this file type.
| var Button = React.createClass({
|   propTypes: {
|     ...TouchableOpacity.propTypes,
|     disabled: PropTypes.bool,
|     style: Text.propTypes.style,

Font Family Issue

I cannot seem to change the font family property of the button text here is what i have:

<Button onPress={() => this.validateUser()} style={styles.btnSignIn} containerStyle={styles.btnContainerSignIn}>SIGN IN</Button>

The styling is as follows:
btnContainerSignIn: { paddingTop: 12, paddingBottom: 12, marginLeft: -5, marginRight: -5, backgroundColor: '#386376', borderRadius: 3, }, btnSignIn:{ color: '#fff', fontFamily: 'Arimo', },

The font family is Arimo and it has been imported properly and seems to be working everywhere else except the button. Anyone know a way around this?

iOS UIButton image support

Consider a simple 'favourite' button. Initially, an empty heart is shown. When pressed, a filled heart is shown.

With a UIButton, you would normally go to your Storyboard and set images for the various states that your button could take: e.g. UIControlStateNormal, UIControlStateHighlighted, UIControlStateSelected, UIControlStateDisabled.

Since the implementation of this button wraps TouchOpacity + Text, I suppose it's possible to wrap TouchOpacity + Image?

Slow motion

By including this package and button component IOS app runs on slow motion.

fontFamily not working on Android

Hi, thanks for writing this library. I used a TypoGraphica font on the button and it worked on iOS but not on Android. I am pretty sure I used the fonts correctly on Android as the fontFamily worked in other places in my app on Android. This is how I used it:

<Button
            containerStyle={styles.my_btn}
            style={{
              fontSize: 20,
              fontFamily: 'typographica',
              color: 'black'
            }}
            onPress={this.goToNext.bind(this)}>
            Press me !
 </Button>

I will be really appreciated If you could have a look.

Thanks

cannot find React

please modify this line:
import { Component, PropTypes } from 'react';
to
import React,{ Component, PropTypes } from 'react';

in Button.js

Disabled Style

Hi , Is there a way to change disabledStyle for container?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.