Reputation: 4192
I want to achieve the next result:
When i start type on each row from textarea
input, to add at the beginning of the textarea
this symbol: +
.
The scenario is next:
+
at the beginning of the row.+
, and so on.
+ text from first row
+ text from second row
+
signs are added every time when i type.Upvotes: 0
Views: 92
Reputation: 106
I would have done it that way
const onChange = e => {
const inputValue = e.target.value;
setState(prevState => {
const newValue = inputValue.startsWith("+")
? inputValue
: `+${inputValue}`;
if (newValue.length < prevState.length && newValue.match(/\n$/)) {
return newValue.replace(/\n$/, "");
} else {
return newValue.replace(/\n(?!\+)$/, "\n+");
}
});
};
https://codesandbox.io/s/priceless-shannon-21j2d?file=/index.js:250-650
Don't forget that accessing the state in a setState isn't a best practice. Prefer to do this like this:
setState(prevState => {
// do what you want with the prevState
return *yourNewState*
})
Upvotes: 0
Reputation: 1
you could do this:
const Text = () => {
const [state, setState] = useState("+");
const onChange = e => {
setState(e.target.value);
};
const enter = e => {
e.persist();
e.preventDefault();
setState(e.target.value + "\n+");
console.log(state);
};
return <TextArea onChange={onChange} onPressEnter={enter} value={state} />;
};
Upvotes: 0
Reputation: 64657
You could do it like this:
https://codesandbox.io/s/interesting-driscoll-2cvfq?file=/index.js:261-525
const onChange = e => {
setState(
e.target.value === "+"
? ""
: (!state ? "+" : "") +
e.target.value
.split(/\n\+$/)
.join("\n")
.split(/\n[^+]/)
.join("\n+")
);
Upvotes: 2
Reputation: 15138
The first idea which comes in mind is, that you check if your last entered key is the enter key like this Stack overflow member did.
But, when I thought of it, it comes to my mind that your idea is not well thought / descriped:
What is, if the user hits the delete key?
Should the "+" be gone?
Or should the "+" be deleted if the row is empty?
Or just add the "+" and don't care any more?
Depending on what you want to show the user with the plus-sign I would try to solve it another way. Maybe add a "+"-Icon in front of each line BEFORE the text, that would be more simple to code, because the user can't interact with the "+".
Upvotes: 0