0

I have a form with a <textarea>. On submit that string gets stored into an array. Sometimes the strings have blank lines or additional spacing and I want to preserve this spacing. Right now, the only spacing preserved is the spacing between words. The handleSubmit component consist of a useRef hook that is pushed into the array. I'm looking for another approach for storing the string that would preserve spacing. I appreciate all ideas! Thank you for your time!

 const textAreaRef = useRef();   
 const [entryArray, setEntry] = useState([]);

 const handleSubmit = (event) => {
        event.preventDefault();
        
        const updatedList = [...entryArray];
        updatedList.push(textAreaRef.current.value);
        textAreaRef.current.value = ""; // Clears value
        setEntry(updatedList);
}

return (
        <div>
        <form class="entryForm"  onSubmit={handleSubmit} >
            <label for="newEntryId"> 
            <span>New Entry:</span>
            <textarea  type="text" id="newEntryId" name="newEntryName" rows="30" cols="75" 
              defaultValue="What's on your mind?" ref = {textAreaRef} 
                /> 
            </label>
            <button type="submit">Submit</button>
       
        </form>
        </div>
    )
1
  • 3
    I suspect this is a fault in debugging assumptions. Are you sure this code is stripping out whitespace? Or are you using some other code to observe the result and not seeing the whitespace? How are you observing it? Are you familiar with how browsers render whitespace? As a guess I suspect what you're actually looking for is a rich text editor plugin of some sort. Commented Aug 10, 2022 at 18:41

1 Answer 1

1

Can't replicate the issue, works fine.

Vanilla js example, but works the same in React

const area = document.querySelector('textarea')
const button = document.querySelector('button')
const saved = []

button.addEventListener('click', () => {
  saved.push(area.value)
  area.value = ''
  console.log(saved)
})
<textarea></textarea>
<button>save</button>

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

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.