0

I am learning react native and I have express.js in the backend and react-native in the front end. I have a multiline textInput like this

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

Then the form is submitted like this.

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

When I send stuff to the database and I render it, it comes back as a single line even if I hit "enter" or line breaks several times. What do I have to do in order to preserve the line breaks created while submitting the form?

craftdeer
  • 985
  • 5
  • 20
  • 36
  • Not really solving the issue you presented, but in general I think it is a bad idea to have database input unfiltered posted... Maybe you can elaborate on what kind of data is being entered within the input? In HTML one could do the `whitespace: pre-wrap` thinggy as mentioned here: https://stackoverflow.com/questions/40417527/how-do-i-preserve-line-breaks-when-getting-text-from-a-textarea/40417702 don't know how to manage that in react-native though. – flaky Apr 17 '18 at 04:41

1 Answers1

0

I think that's because you use json to pass your data.

The first solution is to escape the "\" so it will be:

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

then in your TextInput defaultValue should be something like:

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

Or another one is to convert the \n to something like maybe <br/>. So the code should be the same as above, only change the \\n to <br/>.

DennisFrea
  • 1,112
  • 8
  • 10