Home > database >  React Native: Radio Button group with optional text input
React Native: Radio Button group with optional text input

Time:02-18

I need to build component from the picture. Basically it's regular radio button component, but when the user selects button named 'Other' text input should appear where user can enter custom value.

I already have built the group, I'm just not sure how handle the TextInput part.

What is the best way to structure the component like this?

CodePudding user response:

import React from "react";

export const Radio = () => {
  const [isOtherSelected, setOtherIsSelected] = React.useState(0);
  const [value, setValue] = React.useState("0");
  return (
    <div>
      <input
        type="radio"
        value="Other"
        checked={isOtherSelected}
        onChange={setOtherIsSelected(!isOtherSelected)}
      />
      {isOtherSelected ? (
        <input value={value} onChange={(e) => setValue(e.target.value)}></input>
      ) : (
        ""
      )}
    </div>
  );
};

Just render text input if "other option" is checked. Control value of this input in state.

CodePudding user response:

Simple minified example

import * as React from 'react';
import { View } from 'react-native';
import { RadioButton, Text ,TextInput} from 'react-native-paper';

const MyComponent = () => {
  const [value, setValue] = React.useState('rent');
const [otherPayment,setOtherPayment] = React.useState('');
  return (

    <View style={{padding:15}}>
    <RadioButton.Group onValueChange={newValue => setValue(newValue)} value={value}>
      <View style={{flexDirection:'row',alignItems:"center"}}>
        <Text>Rent</Text>
        <RadioButton value="rent" />
      </View>
      <View style={{flexDirection:'row',alignItems:"center"}}>
        <Text>Other</Text>
        <RadioButton value="other" />
      </View>

      
    </RadioButton.Group>

    {value === 'other' && <TextInput placeholder="Other Payment method" onChangeText={text=> setOtherPayment(text)}/>}
    </View>
  );
};

export default MyComponent;

Expo snack - https://snack.expo.dev/@emmbyiringiro/77f4e2

  • Related