GithubHelp home page GithubHelp logo

thakurballary / react-native-radio-buttons-group Goto Github PK

View Code? Open in Web Editor NEW
241.0 3.0 69.0 1.26 MB

Simple, best and easy to use radio buttons for react native apps.

License: MIT License

TypeScript 100.00%
react-native react-native-radio-buttons radio-buttons simple-radio-buttons ios android form react-native-component radio-buttons-group radio

react-native-radio-buttons-group's Introduction

React Native Radio Buttons Group

Simple, best and easy to use radio buttons for react native apps.

npm LICENSE MIT

NPM

Getting Started

Just a sneak peek (lots more can be done)

DEMO

Installation

npm i react-native-radio-buttons-group --save

or

yarn add react-native-radio-buttons-group

Usage

JavaScript Example
App.js
import React, { useMemo, useState } from 'react';
import RadioGroup from 'react-native-radio-buttons-group';

export default function App() {

    const radioButtons = useMemo(() => ([
        {
            id: '1', // acts as primary key, should be unique and non-empty string
            label: 'Option 1',
            value: 'option1'
        },
        {
            id: '2',
            label: 'Option 2',
            value: 'option2'
        }
    ]), []);

    const [selectedId, setSelectedId] = useState();

    return (
        <RadioGroup 
            radioButtons={radioButtons} 
            onPress={setSelectedId}
            selectedId={selectedId}
        />
    );

}
TypeScript Example
App.tsx
import React, { useMemo, useState } from 'react';
import RadioGroup, {RadioButtonProps} from 'react-native-radio-buttons-group';

export default function App() {

    const radioButtons: RadioButtonProps[] = useMemo(() => ([
        {
            id: '1', // acts as primary key, should be unique and non-empty string
            label: 'Option 1',
            value: 'option1'
        },
        {
            id: '2',
            label: 'Option 2',
            value: 'option2'
        }
    ]), []);

    const [selectedId, setSelectedId] = useState<string | undefined>();

    return (
        <RadioGroup 
            radioButtons={radioButtons} 
            onPress={setSelectedId}
            selectedId={selectedId}
        />
    );

}

Props

RadioButton

Key Type Required Default Valid Values
accessibilityLabel string no Value of label any string
borderColor string no color css color formats
borderSize number 2 positive numbers
color string no #444 css color formats
containerStyle object no react style
description ReactNode or string no any react node or string
descriptionStyle object no react style, applied only if description is a string
disabled boolean no false true / false
id string yes unique string
label ReactNode or string no any react node or string
labelStyle object no react style, applied only if label is a string
layout enum no row row / column
onPress function no any function
selected boolean no false true / false
size number no 24 positive numbers
testID string no any string
value string no any string

RadioGroup

Key Type Required Default Valid Values
accessibilityLabel string no any string
containerStyle object no react style
labelStyle object no react style
layout enum no column row / column
onPress function no any function
radioButtons array yes array of RadioButton objects
selectedId string no unique string
testID string no any string
Horizontal (side by side)
<RadioGroup 
    radioButtons={radioButtons} 
    onPress={onPressRadioButton} 
    layout='row'
/>

Contributions

Fork and create a pull request

License

MIT License

Stargazers over time

Stargazers over time

Sponsor

Buy Me A Coffee

react-native-radio-buttons-group's People

Contributors

a7medev avatar arifemir avatar briannafair avatar despin avatar foxten avatar haschikeks avatar himan7991 avatar jdrodriguezh avatar rafaelcalhau avatar ryosukemochizuki avatar sclavijo93 avatar stefanluecke avatar taeh98 avatar thakurballary avatar tombyrer avatar yuricorrea 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

react-native-radio-buttons-group's Issues

LabelStyle from RadioButton not being considered, only labelStyle from RadioGroup is.

The current RadioGroup definition presents a problem because the labelStyle that is being applied on each RadioButton is the one that comes from Props, regardless of whether the RadioButton already has a labelStyle.

It should check if each button already has a labelStyle in the object, and if it doesn't it defaults to the one from the Props. Please take a look at the comments on the code below for better context.

export default function RadioGroup({
  accessibilityLabel,
  containerStyle,
  labelStyle, /* <-- THIS IS THE ONLY LABELSTYLE THAT IS BEING CONSIDERED WHEN RENDERING */
  layout = 'column',
  onPress,
  radioButtons,
  selectedId,
  testID
}: RadioGroupProps) {

  function handlePress(id: string) {
    if (id !== selectedId && onPress) {
      onPress(id);
    }
  }

  return (
    <View
      accessibilityLabel={accessibilityLabel}
      accessibilityRole="radiogroup"
      style={[styles.container, { flexDirection: layout }, containerStyle]}
      testID={testID}
    >
      {radioButtons.map((button) => ( /* <-- IT NEVER CONSIDERS IF button HAS A LABEL STYLE */
        <RadioButton
          {...button}
          key={button.id}
          labelStyle={labelStyle} /* <-- APPLIES LABELSTYLE FROM PROPS, IGNORING LABELSTYLE FROM button */
          selected={button.id === selectedId}
          onPress={() => handlePress(button.id)}
        />
      ))}
    </View>
  )
}

borderColor and color Props are not working

I've added the component in my React Native project, facing issues with the props "borderColor" and "color". It's giving me the following error:
Type '{ radioButtons: { id: string; label: string; value: string; }[]; onPress: (id: string) => void; selectedId: string | undefined; borderColor: string; }' is not assignable to type 'IntrinsicAttributes & RadioGroupProps'.
Property 'borderColor' does not exist on type 'IntrinsicAttributes & RadioGroupProps'.

Please check the attached image and let me know if I'm doing anything wrong.
image

Don't import the whole lodash library

You are importing the whole lodash library for a single function. This is a terrible pattern and will bloat the bundle, since there is no tree shaking at all.

If you just need isEqual, please use it like this:

npm install --save lodash.isequal
# or
yarn add lodash.isequal

and import

import isEqual from 'lodash.isequal';

Setting a selected option with UseEffect doesn't work

Hello,

Here is a snack to show the issue.

https://snack.expo.dev/@jerrybels/react-native-radio-buttons-group-example

Selecting one of the options in useEffect doesn't work as expected - the option isn't selected. I found out that it is selected if the state is initialized with an empty array :

const [radioButtons, setRadioButtons] = useState([]);

I don't really understand why. It's like the state is initialized after the effect took place? But then why aren't the options disappearing?

Thanks ahead.

label color

i want to change to color of the label
how do i do that??

How to align left the radio button

I have all items aligned left but radio button since thers is some space between left border and small circle of radio button.
Is there any setting to align the button left, i.e. get rid of small space mentioned above...thanks

Add support to add custom styles

Can't give custom styles to the container. In my case Radios are not taking full space. So to do I have to provide custom styles like width: '100%', flexDirection: 'space-around', which is not possible.

labelStyle is missing in the Type definitions

The RadioGroup component has a labelStyle prop, as denoted in the Readme. The prop works, but seems not to be defined in the components type definitions. I need to use @ts-ignore to make the code compile.

...
        <RadioGroup
            radioButtons={radioButtons}
            onPress={onChange}
            selectedId={props.value}

            // @ts-ignore this props is not defined in the typings, but exists
            labelStyle={stylesheet.label}
        />

How to Change borderColor

Hi,
I'm not able to change borderColor of the radio buttons. Can you please guide me on how to change it?
Below is my code:

<RadioGroup radioButtons={radioButtons} onPress={onPressRadioButton} containerStyle={{alignSelf: 'flex-start'}} borderColor={'#E6A4AA'} />

`onPress` of `RadioButtonProps` is always ignored.

Hey,

I just noticed that, when you supply a onPress in the RadioButtonProps, it is always overwritten from the RadioGroup.

        <RadioButton
          {...button}
          key={button.id}
          labelStyle={labelStyle}
          selected={button.id === selectedId}
          onPress={() => handlePress(button.id)}
        />

In a previous version the onPress looked like this

onPress={(id: string) => {
  handlePress(id);
  if (button.onPress && typeof button.onPress === 'function') {
    button.onPress(id);
  }
}}

which I would prefer.

Color prop not used

Color prop is not being used while displaying label and description of the radio button.

Background image in Label

Hi there. Is there a way to set a background image for the radio button labels? I tried with labelStyle with no positive results. Any way to use or component?

Text Styling

I wanna ask if I can change (for example) the size of the labels not just the circle

[ENHANCEMENT] Default Selection based on props

Consider I have category state with value either A,B,C intialized by navigation props

I declared radio state as per docs with labels and value

I want the initial radio selected as per

This.state.radio.value == this.state.category

Thanks from future ! ๐Ÿ‘

Circular Dependency Warning

Circular dependency warning when using the library. I get the following error on the react native app am using this on:

WARN Require cycle: node_modules\react-native-radio-buttons-group\lib\index.ts -> node_modules\react-native-radio-buttons-group\lib\RadioGroup.tsx -> node_modules\react-native-radio-buttons-group\lib\index.ts

As this is an error occurring in the library, it needs to be fixed at the source.

Typescript issue with lodash function

Since I bumped to RN 0.71.0, I've changed some eslint rules, and I have a Typescript error from this lib, which says that a declaration file is missing for 'lodash.isequal', in RadioGroup.tsx file.

Can it be fixed ?

Here is the full description :

TS7016: Could not find a declaration file for module 'lodash.isequal'. '/Users/xxxx/node_modules/lodash.isequal/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/lodash.isequal` if it exists or add a new declaration (.d.ts) file containing `declare module 'lodash.isequal';`

onPress called with button ID

onPress function is called with button.id
woould be more powerful to call onPress with button, so that one can get label, value and id

multi select

Hi, thanks for great library.
I want to allow multi select, how can I do it? Thanks so much

Bug: updating the radioButtons prop of a RadioGroup component doesn't update its options

Bug description

Hello, I hope this finds you well.

I have found that when you pass a new or changed radioButtons prop to a RadioGroup component its options do not update.

Please could you fix this issue? Thank you in advance for your time and effort.

To reproduce

  1. Clone the repo https://github.com/taeh98/react-native-radio-buttons-group-not-updating
  2. Install and link the dependencies
  3. Run the repo with "expo start"

Desired and expected behavior

The behaviour that I expected and desired was that when you update the radioButtons prop given to a RadioGroup component, its radio button options would update if they were changed. For example, you should be able to update the label or colour of a RadioButtonProps option in the RadioGroup component.

Actual behavior

I have found that when you update the radioButtons prop given to a RadioGroup component, its radio button options do not update. Every field of each RadioButtonProps option stays the same apart from the selected option, which appears to update automatically when the selected option changes - so I assume that this too cannot be changed manually.

Environment info

For package versions etc, see https://github.com/taeh98/react-native-radio-buttons-group-not-updating/blob/main/package.json

Radiobuttons without the label

Hi, great thanks for your library
I need to use it without the label text, you can check the UI here http://take.ms/SWBDO
Is there any way to hide the label text now?

I was trying to use label:' ' , but the radios work wrong in this way.

Allow `ReactNode` as a `label` of `RadioButton`

Hey,

I would be interested to see if the label prop of the RadioButton could accept a ReactNode instead of a string.

An example of what I want to achieve is shown in the screenshot, where I have some additional text with a different styling. Or even a text input. This is from a webapp.
This would also allow people to use any themed Text components they might have, without having to override the labelStyle prop.

Screenshot 2024-02-27 at 14 09 58

I reckon, the code would look something like

const labelComp = (typeof label === "string" || typeof label === "number") ? <Text style={[margin, labelStyle]}>{label}</Text> : label;

This should keep it backwards compatible.

The docs then should probably state, that labelStyle is ignored if the label Prop is not a string.

A similar thing could be done for the descriptionprop.

I would be willing to contribute a PR for this.

Can't set radio label color

I can't set radio label color. The initialize color is black but I want white.
Hope fix this issue and update asap.

setfunction of react hook inside onPress not working !

`
const [gender,setgender] = useState('Male');

const radioButtonsData = [{
    id: '0', // acts as primary key, should be unique and non-empty string
    label: 'Male',
   /// value: 'option1'
}, {
    id: '1',
    label: 'Female',
   /// value: 'option2'
}, {
    id: '2',
    label: 'Gay',
   /// value: 'option2'
}
, {
    id: '3',
    label: 'Straight',
}
]

const [radioButtons, setRadioButtons] = useState(radioButtonsData);


function onPressRadioButton(radioButtonsArray) {
    setRadioButtons(radioButtonsArray);
    console.log(radioButtonsArray);
    for(let j=0;j<radioButtonsArray.length;j++)
    {
        if(radioButtonsArray[j].selected==true)
        {
            setgender(radioButtonsData[j].label)
            console.log(j)
        }
    }
    console.log(gender);
}

return (
    <View style={{ flex: 1 }}>

        <View style={{ width: '92%', alignSelf: 'center', padding: 10 }}>

            <Text style={{ fontWeight: 'bold', fontSize: 18 }}>Sexual Orientation</Text>

            <View style={{alignSelf:'center'}}>
            <RadioGroup
                radioButtons={radioButtons}
                onPress={onPressRadioButton}
            />
            </View>

        </View>

    </View>
)`

Can you plz tell ? why inside onpress , another state is not updating ? What is the usage of this library ?

Mutates original object

Hi, I'm using this component for an app. I followed the docs, though ran into trouble where it will mutate the original object, and never reset it back when the parent component unmounts/remounts. When it gets re-mounted it contains same values as the last time it was modified, it does not revert back to the original object! :*(

For the example the code is shown in docs as follows (added notes as comments):

import React, { useState } from 'react';
import RadioGroup from 'react-native-radio-buttons-group';

const radioButtonsData = [{  // <-- ORIGINAL OBJECT
    id: '1', // acts as primary key, should be unique and non-empty string
    label: 'Option 1',
    value: 'option1'
}, {
    id: '2',
    label: 'Option 2',
    value: 'option2'
}]

export default function App() {

    const [radioButtons, setRadioButtons] = useState(radioButtonsData) // <--- PASSING ORIGINAL OBJECT

    function onPressRadioButton(radioButtonsArray) {
        setRadioButtons(radioButtonsArray);
    }

    return (
        <RadioGroup 
            radioButtons={radioButtons} 
            onPress={onPressRadioButton} 
        />
    );
}

I believe the problem is here (RadioGroup.tsx):

export default function RadioGroup({ containerStyle, layout = 'column', onPress, radioButtons }: RadioGroupProps) {

  const [radioButtonsLocal, setRadioButtonsLocal] = useState<RadioButtonProps[]>(radioButtons); // <-- this is OK

  if(!isEqual(radioButtons, radioButtonsLocal)) {
    setRadioButtonsLocal(radioButtons); 
  }

  function handlePress(id: string) {

    
     console.log("Same object ref?:", radioButtonsLocal === radioButtons); // <--- TRUE!

    for (const button of radioButtonsLocal) {
      if (button.selected && button.id === id) return;
      button.selected = button.id === id;   // <--- MUTATING ORIGINAL OBJECT radioButtonsData
    }
    setRadioButtonsLocal([...radioButtonsLocal]);
    if (onPress) {
      onPress(radioButtonsLocal);
    }
  }

Is this expected behavior? Currently, the workaround I am doing is to put the object inside the component so that it gets recreated each time fresh.

import React, { useState } from 'react';
import RadioGroup from 'react-native-radio-buttons-group';

export default function App() {

 const [radioButtons, setRadioButtons] = useState([  // <-- placed inside of component
    {
      id: "1", // acts as primary key, should be unique and non-empty string
      label: "Option 1",
      value: "option1",
    },
    {
      id: "2",
      label: "Option 2",
      value: "option2",
    },
  ]);

    function onPressRadioButton(radioButtonsArray) {
        setRadioButtons(radioButtonsArray);
    }

    return (
        <RadioGroup 
            radioButtons={radioButtons} 
            onPress={onPressRadioButton} 
        />
    );
}

text color is not getting apply

<RadioGroup
labelStyle={{color: this.context.basicFontColor,}}
containerStyle={{
alignItems: 'flex-start',
color: this.context.basicFontColor,
backgroundColor:this.context.surfaceColor == '#1A1D21' ? '#2c2c2c' : this.context.surfaceColor
}}
descriptionStyle={{color: this.context.basicFontColor}}
textColor={{color: this.context.basicFontColor}}
color={this.context.basicFontColor}
selected={true}
radioButtons={viewButtonsData}
onPress={this.selectReqMethod}
/>

No support for testID on button

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

I added button support because I am applying e2e Test with BDD and I saw that the component was not supported.

diff --git a/node_modules/react-native-radio-buttons-group/lib/RadioButton.tsx b/node_modules/react-native-radio-buttons-group/lib/RadioButton.tsx
index db1dcac..ee598ad 100644
--- a/node_modules/react-native-radio-buttons-group/lib/RadioButton.tsx
+++ b/node_modules/react-native-radio-buttons-group/lib/RadioButton.tsx
@@ -18,6 +18,7 @@ export default function RadioButton({
   selected = false,
   size = 24,
   borderSize = 2,
+  testID,
 }: RadioButtonProps) {
 
   const borderWidth = PixelRatio.roundToNearestPixel(borderSize);
@@ -45,6 +46,8 @@ export default function RadioButton({
     <>
       <Pressable
         onPress={handlePress}
+        testID={testID}
+        accessibilityLabel={testID}
         style={[
           styles.container,
           orientation,
diff --git a/node_modules/react-native-radio-buttons-group/lib/types.ts b/node_modules/react-native-radio-buttons-group/lib/types.ts
index 511f431..9d1e46d 100644
--- a/node_modules/react-native-radio-buttons-group/lib/types.ts
+++ b/node_modules/react-native-radio-buttons-group/lib/types.ts
@@ -14,6 +14,7 @@ export type RadioButtonProps = {
   size?: number;
   value?: string;
   borderSize?: number;
+  testID?: string;
 };
 
 export type RadioGroupProps = {

This issue body was partially generated by patch-package.

row overflows from the screen

RadioGroup row feature overflows from the screen

  <RadioGroup
      layout="row"
      radioButtons={[
            {id: '1', label: "now", value: 0, selected: true},
            {id: '2', label: "10s", value: 10000, selected: false},
            {id: '3', label: "30s", value: 30000, selected: false},
            {id: '4', label: "1m", value: 60000, selected: false},
            {id: '5', label: "5m", value: 300000, selected: false},
      ]}
      onPress={(e)=>console.log(e)}
    />

Accesibility is missing

I want to used it for my own library components but it doesnt have any accessibility prop and its a requeriment in the proyect Im working on, its something easy to add and it would not take more than a few lines. I think its a good improvement to have it

Styling the radio group?

i am try to style radio buttons,circle but nothing change i read doc and example but there is no example with styling. i am using this
color="#ffffff" containerStyle={{ color:" #FFFFFF" }} labelStyle={{ color:" #FFFFFF" }}

borderColor and labelStyle props are not working.

When I try using the "borderColor" prop, it typescript alway throws this error and it dose not work at all.

Type '{ containerStyle: { width: "100%"; display: "flex"; alignItems: "flex-start"; flexDirection: "column"; gap: number; marginTop: number; }; borderColor: string; radioButtons: { id: string; label: string; value: string; }[]; onPress: (item: string) => void; selectedId: string | undefined; }' is not assignable to type 'IntrinsicAttributes & RadioGroupProps'.
Property 'borderColor' does not exist on type 'IntrinsicAttributes & RadioGroupProps'.

Touch area is too small or unconfortable.

When it comes to mobile app design, the radio button touch area shall be bigger.

What you can do is increase the touch area by using the hitSlop property eg:

                        <TouchableOpacity
                            hitSlop={{ top: 30, right: 30, bottom: 30, left: 30 }}
                        >
                        </TouchableOpacity>

Also, the touch area still will be small IMO. Allow users to select the radio button by touching on the description/title of the radio button...

Ty for the lib! ๐Ÿ˜˜

[REQUEST] No default selection

The component is always selecting the first Radio by default, it would be nice if we could disable this behavior, it's not a good practice to leave something pre-selected to the user as it may interfere with its choices.

when setting state in onpress the inner circle does not show- the selected one

<Common.RadioGroup
radioButtons={[
{
id: '1',
label: 'ืื•ืคืฆื™ื” 1',
value: 'option1',
color: 'blue',
layout: 'row',
size: 24,
},
{
id: '2',
label: 'ืื•ืคืฆื™ื” 2',
value: 'option2',
layout: 'row',
size: 26,
},
]}
layout={'row'}
onPress={arr=> {
console.log('pressed group')
let sel=arr.find(e => e.selected)?.value
this.setState({radio_selected:sel})
}}
containerStyle={{ backgroundColor: 'yellow' }}
/>

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.