Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Visualize onkeypress line breaks in textarea with REACT

what is a valid approach to visualize a text created inside a textarea element with the correctly assigned line breaks?

As soon as I input a line break by pressing Enter key, I can see that this is displayed inside the textarea correctly but when I visualize the output in another element, the line break appears as a space. The data is also saved in my database without any line breaks.

I have attached a sample code to the link below: https://codesandbox.io/s/busy-hodgkin-1oujz?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The easiest way would be through CSS, by following:

...
<div className="App">
  <div className="wrapper">
    <div>
      <p class='formatted'>{text}</p>
    </div>
...

And then: .formatted { white-space: pre; }

Another way would be using dangerouslySetInnerHTML:

...
<div className="wrapper">
  <div>
    <p
      dangerouslySetInnerHTML={{
        __html: formattedText,
      }}>
    </p>
  </div>
...

And the logic to handle that would be:

const [text, setText] = useState('');
const [formattedText, setFormattedText] = useState(text);

const handleTextInput = ({ target }) => {
  const { value } = target;
  const formattedValue = value.replace(/\n/g, '<br />');

  setText(value);
  setFormattedText(formattedValue);
};
about 4 years ago · Juan Pablo Isaza Report

0

There's some possible approachs to your problem. In few words, \n new line characters on textarea does not work on plain html. Instead, we could use <br />.

Instead of simply rendering text as it's stored, you could split into new lines and render <br /> in its place:

      <p>
        {text.split('\n').map((subtext) => (
          <>
            {subtext}
            <br/>
          </>
        ))}
      </p>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!