I’m working on a React native project, and I’m using the useState hook and the TextInput property to store the user’s input, I associate these inputs to a text component so that they are rendered and displayed every time the user types a number.
const BMIcalculator = () => {
const [state, setState] = useState([""]);
function userHeightHandler(value) {
for (var i = 0; i < value.length; i++) {
if (value[i].length == 1) {
var res = value.splice(1, 0, ".");
setState(res.join(""));
}
}
setState(value);
return (
<View style={styleInside.heightContentValue}>
<Text style={{ justifyContent: "center", fontSize: 22 }}>
{"text: " + state +}
</Text>
</View>
<View style={styles.input}>
<Input
style={styles.inputs}
placeholder="text"
maxLength={3}
onChangeText={(value) => userHeightHandler([value])}
}
/>
</View>
)
}
My goal is to be able to concatenate a "." after the first character the user types, and have this value remain until removed, how could I do this? It may seem like a simple thing, but it’s taken me all day trying to figure it out, I’d appreciate any advice or help in advance.
3
Answers
If I understand correctly, you want to add a "." at the end of the user input when its length is equal to one.
Try this:
You can see a working example in React:
CodeSandBox
So if I understand correctly, what you try to achieve is to insert a ‘.’ character after the first character of your input as long as your input has at least one character?
Here is how it could be done assuming you don’t want to update the input value itself but just the state that is displayed in the Text block.
Note if you want to update the input itself, you would probably need more advance stuff like handling the cursor after the user inputs the first character or handling backspace behaviour when the user presses it from behind the first character or behind the
.
character. Additionally you might want to add some checks so that the user can only input numbers.If you don’t care about edge case or weird caret behaviour, you can do the following:
Both, using a
[""]
for your state and youruserHeightHandler
look way too complicated to me.something like this?
this shouldn’t be too hard to translate to react. something like
You even get
prev
for free when doingsetState(prev => ...)