Home > database >  React: How to clear TextArea?
React: How to clear TextArea?

Time:11-18

I know how to control input component. But this behaviour I didn't understand at all.
I have antd form with textarea in it.

<Item
  name='tags'
  className='input-item tag-helper'
  label='These are tags that appear on your NFT'
>
  <TextArea value={text} className='big-text-area tag-text-area' placeholder='Enter a tag...' onKeyDown={addTag} />
</Item>

The textArea responsible for adding tags. So when I write something in input It controls by useState variable and after space press, It's added to an array with tags. After space press, input has to clear but nothing happens.
My code looks like this right now:

  const addTag = value => {
    setText(value.target.value)
    if (value.keyCode === 32) {
      setTags([...tags, text])
      setText('')
    }
  }

In earlier version:

const addTag = value => {
  if (value.keyCode === 32) {
    setTags([...tags, text])
    setText('')
  }
}

<Item
  name='tags'
  className='input-item tag-helper'
  label='These are tags that appear on your NFT'
>
  <TextArea value={text} className='big-text-area tag-text-area' placeholder='Enter a tag...' onKeyDown={addTag} onChange={v => setText(v.target.value)} />
</Item>

Also, I thought that It a good idea to try setting text through useEffect, so I experimented and added the last one func:

useEffect(() => {
    setText('')
}, [tags])

Can somebody say me what I'm doing wrong? Why I can't clear textArea after I press "space"?

CodePudding user response:

It could be something regarding the fact that you are not passing an onChange prop to TextArea so it is not in controlled mode and it is ignoring the value prop you are passing to it. You could try this:

<TextArea value={text} onChange={() => {}} className='big-text-area tag-text-area' placeholder='Enter a tag...' onKeyDown={addTag} />

or you can do this in the onChange

const onChange = (e) => {
  const currentText = e.target.value;
  if(currentText.length && currentText[currentText.length - 1] === " "){
    setTags([...tags, text]);
    setText("");
  } else {
    setText(e.target.value);
  }
}

and leave the TextArea like this

<TextArea value={text} onChange={onChange} className='big-text-area tag-text-area' placeholder='Enter a tag...' />

CodePudding user response:

Adding event.persist(); worked for me.

const addTag = event => {
   event.persist();
   
   if (event.keyCode === 32) {
     setTags([...tags, text])
     setText('');  
   }else{
     setText(event.value);
   }
};
  • Related