'React Native: Radio Button group with optional text input
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?
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | skelaw |
| Solution 2 | Shy Penguin |
