What is the best way to preserve line breaks in a React Native database using the <pre> tag or a similar method?

I am currently diving deep into learning React Native with Express.js on the backend and React-Native on the frontend. I have implemented a multiline TextInput in my form like below:

  <TextInput
      style={{ textAlign: 'center', fontSize: 22 }}
      multiline = {true}
      numberOfLines = {4}
      ....
  />

After inputting data, the form is submitted using the following code snippet:

onQuestionSubmit() {
   fetch('url', {
    credentials: 'same-origin',
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
     databaserow: this.state.blahblah,
   }),
  })
 }

However, when I retrieve and render the data from the database, it appears as a single line even if I pressed "enter" for line breaks while entering the text. How can I maintain the line breaks when submitting the form?

Answer №1

One reason for this issue could be the usage of JSON to transmit your data.

An initial remedy is to add an escape character "\" like this:

  onQuestionSubmit() {

   var blah = this.state.blahblah;
   blah = blah.split('\n').map((item, key) => {
     return item+'\\n'
   }).join('');

   fetch('url', {
    credentials: 'same-origin',
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
     databaserow: blah,
   }),
  })
 }

In your TextInput, the defaultValue should look something similar to this:

defaultValue={this.state.blahblah.split("\\n").join('\n')}

Alternatively, you can change the \n to a different format like maybe <br/>. The code structure would remain the same as above, but replace \\n with <br/>.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The division is now appearing below the preceding division instead of following it

I am currently encountering an issue that I believe has a simple solution, but I am unable to find it. I have two divs in my code. The first div contains a blurred background image and content, which is working perfectly fine. However, the second div is n ...

Interactive Navigation System Featuring Nested Dropdowns in HTML and CSS

I've been working on creating a customized navigation bar with sub menus using simple coding to keep it lightweight, but I'm encountering issues with the functionality. Could you please take a look at this code and fiddle link: Fiddle https://jsf ...

Mastering the Art of jQuery: Easily Choosing and Concealing a Div Element

I'm currently facing challenges in removing a div upon successful AJAX completion. The issue I'm encountering is that the word "Added" appears twice after success, indicating that I am not properly selecting the two divs containing it. Any sugges ...

PostgreSQL is indicating that a relation is not present, even though the table itself does exist

I'm currently working on integrating my express app with a Postgres database. Below is the snippet of my code: var express = require('express'); var app = express(); var pg = require('pg').native; var connectionString = process.en ...

Is there a way to conceal a Select element so that it is not visible on the screen, yet can still activate the dropdown menu when another element is clicked

One idea for my website is to replace a select element with a button that triggers the dropdown. The plan is to place the select element inside a button DIV, position the select element on top of the button, and set its opacity to 0 so it appears hidden. W ...

Numerous sections of content

Struggling to align these two pieces of content side by side. While I've had success displaying content like this in the past, I'm hitting a roadblock this time around. Any assistance would be greatly appreciated. HTML <div class="block-one" ...

Error in JavaFX: CSS Parser anticipating COLON

Encountered an error and struggling to find the issue as everything seems right from my perspective: CSS Code: @font-face { font-family: 'Titillium'; font-style: normal; font-weight: normal; src: url('Titillium.ttf'); ...

Error: JSON parsing failed due to an unexpected token 'e' at index 3

After installing the latest version of "body-parser": "^1.18.3" and adding the line express.use(bodyParser.json());, I encountered an issue where my routes were functioning properly but req.body was always returning as undefined. I have not used JSON.parse ...

Establish a primary background color for the React application, with the majority of the display content

I have been working on styling a React project where App.js mainly handles routing and navigation to its components: App.js import {useState, useEffect} from 'react'; import Models from './pages/Models'; import Loadingpage from ' ...

Displaying a dropdown menu from the top by utilizing the show() function

I've successfully implemented a dropdown menu using cssmenumaker. It works perfectly on desktop and mobile view. However, I'm facing an issue on mobile where the dropdown menu slides in from the left when clicked. I would prefer it to slide down ...

Is this the correct method for constructing a class in CSS?

What is the correct way to style a class with CSS and write HTML code? .first{ color:red; } Here is an example of HTML code: <class id=first> <p> some text </p> <p> some other text </p> ...

What should be included in the get/set/destroy functions for a koa-session database instance?

I'm facing an issue with storing the sessions of my Koa app on a mongo DB server. The problem lies in this part of the documentation that I find confusing: https://github.com/koajs/session/blob/master/Readme.md#external-session-stores It mentions th ...

Getting the name and value from an object

Just starting out with Javascript and Nodejs, using express and making a call to the following link: localhost:7080/v1/movies/order/notify/insert?breed=Whippet&age=10 After that, I am attempting to extract the property name along with its correspon ...

JQuery is capable of hiding a div using the .hide() method but is unable to reveal it using the

I am currently working on a basic webpage that includes a question and a set of radio buttons. Depending on the option selected by the user, the question will be hidden and either a correct or incorrect message will be displayed, both of which are initiall ...

The issue regarding the fixed table layout bug in Firefox

Upon testing Firefox 5, it has come to my notice that an additional pixel of space is being added between the right column and the table border due to this particular piece of code: <style type="text/css"> table { border: 1px s ...

The user can witness the appearance of a scrollbar when utilizing the

Struggling to remove the scroll bar from my ion-scroll. Have tried various methods but nothing seems to work. Need assistance with this, please! Attempted using all attributes and even used CSS like ::-webkit-scrollbar with display: none;, which hides it ...

Creating a new music application and looking for ways to keep track of and update the number of plays for

I'm currently developing a music app and am looking for a way to update the play count every time a user listens to a song for at least 30 seconds. I've attempted the following approach: let current_final; let current_initial; ...

Tips for displaying specific information using Javascript depending on the input value of an HTML form

I am working on an HTML form that includes a dropdown list with four different names to choose from. window.onload = function(){ document.getElementById("submit").onclick = displaySelectedStudent; } function displaySelectedStu ...

react-native-track-player failing to play song requested from Express server

I set up an expressjs server with a 'songs' route that serves .mp3 files. Here is the code for the Songs Route: import express from "express" const path = require("path") const router = express.Router() ... router.get(" ...

Enable the expansion of a div by dragging and dropping an image onto it

Take a look at this fiddle. In this fiddle, I am able to drag and drop images onto the .drop-zone. However, I would like to enhance it so that when I drag an image onto it, the .drop-zone div expands to where I place the image. It's okay if the expand ...