Skip to content

Instantly share code, notes, and snippets.

@majudhu
Last active May 3, 2021 10:34
Show Gist options
  • Save majudhu/0dd88f9ae126f8a0870850da0dcd78f0 to your computer and use it in GitHub Desktop.
Save majudhu/0dd88f9ae126f8a0870850da0dcd78f0 to your computer and use it in GitHub Desktop.
Type in English to Dhivehi Text Input React https://codesandbox.io/s/dv-text-input-89qp4
import React from "react";
import TextField from "@material-ui/core/TextField";
import DvTextField from "./DvTextField";
export default function Demo() {
return (
<>
<DvTextField
ParentComponent={TextField}
customRef="inputRef"
parentProps={{ variant: "outlined" }}
/>
<DvTextField />
<DvTextField ParentComponent="input" />
<DvTextField ParentComponent="textarea" />
</>
);
}
import React, { useState, useEffect, useRef } from "react";
export default function DvTextField({
ParentComponent = "input",
customRef = "ref",
parentProps = {}
}) {
const dvInputRef = useRef();
const options = { [customRef]: dvInputRef };
const [dvText, setDvText] = useState({
value: "",
selectionStart: 0
});
useEffect(() => {
if (dvInputRef.current) {
dvInputRef.current.selectionStart = dvText.selectionStart;
dvInputRef.current.selectionEnd = dvText.selectionStart;
}
}, [dvText.selectionStart]);
return (
<ParentComponent
{...parentProps}
{...options}
value={dvText.value}
onChange={(e) =>
setDvText({
value: e.target.value,
selectionStart: e.target.selectionStart,
selectionEnd: e.target.selectionEnd
})
}
onBeforeInput={(e) => {
if (Object.keys(dvCharMap).includes(e.data)) {
e.preventDefault();
setDvText({
value:
dvText.value.slice(0, e.target.selectionStart) +
dvCharMap[e.data] +
dvText.value.slice(e.target.selectionEnd),
selectionStart: e.target.selectionStart + 1
});
}
}}
/>
);
}
const dvCharMap = {
A: "ާ",
B: "ޞ",
C: "ޝ",
D: "ޑ",
E: "ޭ",
F: "ﷲ",
G: "ޣ",
H: "ޙ",
I: "ީ",
J: "ޛ",
K: "ޚ",
L: "ޅ",
M: "ޟ",
N: "ޏ",
O: "ޯ",
P: "÷",
Q: "ޤ",
R: "ޜ",
S: "ށ",
T: "ޓ",
U: "ޫ",
V: "ޥ",
W: "ޢ",
X: "ޘ",
Y: "ޠ",
Z: "ޡ",
a: "ަ",
b: "ބ",
c: "ޗ",
d: "ދ",
e: "ެ",
f: "ފ",
g: "ގ",
h: "ހ",
i: "ި",
j: "ޖ",
k: "ކ",
l: "ލ",
m: "މ",
n: "ނ",
o: "ޮ",
p: "ޕ",
q: "ް",
r: "ރ",
s: "ސ",
t: "ތ",
u: "ު",
v: "ވ",
w: "އ",
x: "×",
y: "ޔ",
z: "ޒ"
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment