I have a component and use of this component
I can’t write the correct input so that you can enter only numbers without , . and so
on, please help
component
use of component
my component
export default function AppTextInput({icon, placeholder,onChangeText, ...otherProps}) {
const onChanged =(text) =>{
let newText = '';
let numbers = '0123456789';
for (var i=0; i < text.length; i++) {
if (numbers.indexOf(text[i]) > -1) {
newText = newText + text[i];
} else {
alert("please enter integer numbers only");
}
}
}
return (
<View style={styles.container}>
{icon &&
<MaterialCommunityIcons style={{marginRight: 10}} name={icon} color={colors.grayMedium} size={20}/>}
<TextInput style={defaultStyles.text} placeholder={placeholder}
onChangeText={(text)=> onChanged(text)} maxLength={3} {...otherProps}
></TextInput>
</View>
)
}
use of component
<View style={{top: -80}}>
<AppTextInput icon="timer-sand" placeholder={"Prep Time"} keyboardType='numeric' onChangeText={(text) => setPrepTime(text)}/>
<AppTextInput icon="timer" placeholder={"Round Duration"} keyboardType='number-pad' onChangeText={(text) => setRoundDuration(text)}/>
<AppTextInput icon="timer" placeholder={"Break Duration"} keyboardType='number-pad' onChangeText={(text) => setBreakDuration(text)}/>
<AppTextInput icon="repeat" placeholder={"Number of Rounds"} keyboardType='number-pad' onChangeText={(text) => setNumRounds(text)}/>
<AppTextInput icon="format-list-numbered" placeholder={"Number of Sets"} keyboardType='number-pad' onChangeText={(text) => setNumSets(text)}/>
{exerciseInputEles}
</View>
I try this solutions, but it didnt work, i think i don’t understand in what place put and how to use , that it start works.
3
Answers
i try do like that but
when i input alert work, but onChangeText={(text) => setNumRounds(text)} and other don't see my input , why?
First of all, an argument for the onChange event handler is not a new value of the input but an event object. You can access the value by doing something like this:
Here is the code you can use:
onChanged
function you have to the other file and useRegex
to replace the non-digit character with empty string.Aside from that I changed the input value of your
onChangeText
from(text)=> onChanged(text)
toonChangeText
(it’s the props), becauseonChanged
is not there anymore.Here I added the function called
replaceNonNumeric
, the function is used to replace any non-numeric digit to an empty string, so there will be only digit in it.I called
replaceNonNumeric
right before you change the state and passed the new value to thesetState
.