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
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 -
As if JS is not even recognizing \n
!! BUT in the same place when I run it the console I get this -
Thanks in advance!
Please let me know if anything else is needed to understand the problem better
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
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 -
As if JS is not even recognizing \n
!! BUT in the same place when I run it the console I get this -
Thanks in advance!
Please let me know if anything else is needed to understand the problem better
-
1
\n
is not recognized by html input as next line , so you can replace this before providing this value to your input by the asci char
item.description.replace("\n"," ")
– Bourbia Brahim Commented Dec 7, 2020 at 7:37 -
I tried to replace
\n
with ` ` in the MongoDB Cloud document (since data is being received from there) and this is what I got in the Description TextField -* This is line one * This is line two \n*
. Although the
doesn't show in the preview, it does not change the line in the preview too. – viveknigam3003 Commented Dec 7, 2020 at 9:25
2 Answers
Reset to default 3Apparently 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}
/>
Try using <p>
to display ur descriptions. It automatically makes a new line for each element. If that doesn't work use the <br>
tag after every line. You can use it to add a line break manually.