1

if I have something like this:

  return array.map(item => (
<input type="text" value={item.name}> onChange ={(name) => changeItemName(name.target.value)}

where the changeItemName function is basically a function that will change the name attribute of the current item. How can I go about making sure that the name attribute wont have any trailing or leading spaces? I can do something like this in my changeItemName function:

changeItemName(name){
name.trim()
... logic to change name of item }

However since I am using onChange(), this method is called everytime a character is typed. This means that if a user types a regular space between 2 words, this wouldnt work because the name passed into the function would be trimmed thus now allowing any spaces. How can I tweak this so that spaces still work but leading and trailing white spaces are gone?

1

2 Answers 2

1

You can trim the name when the user finished typing. For example when the input got out of focus. Try this:

<input type="text" value={item.name}>
    onChange ={(name) => changeItemName(name.target.value)}
    onBlur={()=> { item.name = item.name.trim() }} 
/>

Here the onBlur function would fire when user goes to some other input or other part of your website.

Sign up to request clarification or add additional context in comments.

2 Comments

This works but wouldnt this mutate the state of item?
I'm not sure what do you mean by mutate. If you mean change the state of the item well yes. It only changes the name but if there is a useEffect (or any part of the app) that reruns when you change the item, it would run when onBlur runs..
0

There are several options, one is to use a debouncing function that will trim the input after the user stops typing for a couple hundred milliseconds. The other option is to trim the input on the blur event.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.