Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New line '\n' not recognized inside TextField in React

Context

I am using Material UI TextField and mapping an array of objects which is fetched from Database (MongoDB). Something like:

{state.map((item) => (
         <TextField
          name="description"
          multiline
          required
          type="text"
          value={item.description}
          onChange={handleChange}
        />)
      )
}

Where state is the array fetched from the database.

Problem

The item.description is displayed as it is with \n escape sequences instead of separating the line into new lines.

Examples

How the input component looks like

How the output is rendered

Additional Info

  • When I try to do console.log(item.description.split('\n')) inside my React code I get the following output in the console -

Console.log output

As if JS is not even recognizing \n !! BUT in the same place when I run it the console I get this -

Console.log running the same command

Thanks in advance!
Please let me know if anything else is needed to understand the problem better

like image 558
viveknigam3003 Avatar asked Dec 04 '25 17:12

viveknigam3003


1 Answers

Apparently I solved this by creating a helper function using replace and regex global search

const parseLines = (value) => value.replace(/(\\n)/g, "\n");

I realized I had to use \\n instead of \n to detect the string pattern of \n and replace it with newline which is simply \n.

And later in in TextField

<TextField               
 name="description"              
 multiline
 required
 type="text"
 value={parseLines(item.description)}
 onChange={handleChange}
/>
like image 95
viveknigam3003 Avatar answered Dec 06 '25 08:12

viveknigam3003



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!