Etika49
Etika49

Reputation: 742

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

Upvotes: 4

Views: 261

Answers (2)

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

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);
};

Upvotes: 3

Canta
Canta

Reputation: 1480

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>

Upvotes: 0

Related Questions