'How to automatically take a '/' (slash) in input field using reactJS
How can I format an input to place a slash before the value that the user enters, so that the user cannot delete it because it is already formatted that way. I'm trying to add functionality to input /characters fields so as when the users enters digits, slashes "/" get automatically added before.
I'm new in React, so I don't any idea of how I can resolve that, please helpe me
An Example of the result I want to resolve
mascaraUserName = (text) => {
const selectedData_ = this.state.form;
formated = text;
if(formated.length==1){
//formated = text +'/';
if(selectedData_.userName.indexOf('/') == -1){
formated = text +'/';
}
}
console.log(formated);
// this.setState({ form: myRef });
}
<Col xs={24} sm={24} md={24} lg={24}>
<FormItem {...formItemLayout}
label={intl.formatMessage({ id: `maintenace.link.userName` })}>
{getFieldDecorator(`disable`, {
initialValue: "https://"
? "https://"
: ""
})(<Input style={{ color: "#3e3e3ed9"}} disabled="disabled"/>)}
{getFieldDecorator(`userName`, {
initialValue: selectedData_.userName
? selectedData_.userName
: ""
})(<Input className="inputLink" name="userName" ref={this.myRef} onChange={this.mascaraUserName} placeholder={intl.formatMessage({
id: `maintenace.link.nicknameIntructions`
})} />)}
</FormItem>
</Col>
Solution 1:[1]
You can make the input controlled and then intercept any change that tries to remove the initial "/":
import React, { useState } from "react";
export default function App() {
const [link, setLink] = useState("/");
return (
<input
value={link}
onChange={(e) => {
const value = e.target.value;
if (!value.startsWith("/")) e.preventDefault();
else setLink(value);
}}
/>
);
}
Edit: Didn't notice this was react native (it's not tagged as it) but I'll leave my answer here since you can probably still use the logic to achieve what you want.
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 |

