Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 676
Etika49 Avatar asked Sep 02 '25 16:09

Etika49


1 Answers

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);
};
like image 165
Samuli Hakoniemi Avatar answered Sep 05 '25 04:09

Samuli Hakoniemi