Am trying to create a text input with multiline in a react native app, so that the user can add some notes. the issue am having is on inserting a bullet on the new line when a return key is pressed inside of that input box. Is there any technique to achieve this?
CodePudding user response:
This could help you.
import { useState } from "react";
export default function App() {
const [text, setText] = useState();
const change = (e) => {
setText(e.target.value);
};
const checkEnter = (e) => {
if (e.key === "Enter") {
console.log(String.fromCharCode());
setText(text "•" " ");
}
};
return (
<div className="App">
<textarea onChange={change} onKeyUp={checkEnter} value={text} />
</div>
);
}
CodePudding user response:
Simply add this into your TextInput
component. The only thing you need to evaluate is the last character typed. You could also use onKeyPress
prop to check if it was a line break but it would overcomplicate, since you cannot prevent line breaks from your onChangeText
onChangeText={(txt) => {
if (txt.substr(-1) === '\n') {
setTypedText(`${txt}*`);
} else {
setTypedText(txt);
}
}}
CodePudding user response:
Here is my answer.
const [text, setText] = React.useState('');
const onChangeText = (newText: string) => {
const bullet = '\u2022';
const isLineBreak = newText.lastIndexOf('\n') === newText.length - 1;
if (isLineBreak) {
setText(newText bullet);
} else {
setText(newText);
}
};
...
<TextInput multiline value={text} onChangeText={onChangeText} />