I have a variable called resultElem which is created after reading an array. As it reads the array, I want to add a newline '\n' or
at the end of it, following a space.
for (let l=0; l<answer.questions.length; l++) {
var questionMap = [answer.questions[l].questionId, answer.questions[l].answers];
let resultElem :any;
for (let m =0; m< employmentAnswerMap[l].answerKVs.length; m++){
if (questionMap[1].includes(employmentAnswerMap[l].answerKVs[m].id)) {
resultElem = resultElem + employmentAnswerMap[l].answerKVs[m].text + ' ' + '\n';// I have tried + '\n' and + 'br'
}
}
result.push(resultElem);
}
I have also tried .appendChild() but I didn't like it since I just want to use resultElem to make the data.
return (
<dl>
<dt>Health Needs</dt>
<dd>{result[0]}</dd>
</dl>
...more ui code
It gets displayed, but as one big text paragraph without newlines, like so
healthNeed1 healthNeed2 healthNeeds3
healthNeed1
healthNeed2
healthNeeds3
I am able to print the strings in seperate line by using '\n'. I am adding demo below. Can you please update that as per the issue you are facing so that we can look into that.
Demo :
const answer = {
questions: [{
questionId: 1,
answers: ['answer1', 'answer2', 'answer3']
}]
};
const employmentAnswerMap = [
{
answerKVs: [{
id: 1,
text: 'healthNeed1'
}, {
id: 2,
text: 'healthNeed2'
}, {
id: 3,
text: 'healthNeed3'
}]
}
];
const result = [];
for (let l=0; l<answer.questions.length; l++) {
var questionMap = [answer.questions[l].questionId, answer.questions[l].answers];
let resultElem = '';
for (let m =0; m < employmentAnswerMap[l].answerKVs.length; m++){
if (questionMap[1].find((elem) => elem.includes(employmentAnswerMap[l].answerKVs[m].id)).length > 0) {
resultElem = resultElem + employmentAnswerMap[l].answerKVs[m].text + ' ' + '\n';
}
}
result.push(resultElem);
}
console.log(result[0]);
HTML doesn't really like to add line breaks, even if you include them. If you have to include them, template literals are the easiest way. To use those, use backticks(`) instead of single(') or double quotes("). Template Literals take literally what you type as the string, and can only be escaped at the end of the string, or by encapsulating your escaped javascript with ${}. It looks like this:
let bob=true;
`Look at me,
I'm using backticks! ${bob ? "No literals here!" : "But you
can use the 'ternary operator'!"}`
Unfortunately, it doesn't look like the code sample likes backticks. But I assure you, they work! Of course, even with the return inside the template literals, HTML is going to mostly ignore them unless you use the new CSS white-space property. You could also add append a new <p> tag for each one, which can be styled however you like, including to make them have a new line.
I had to wrap my HTML around this div in order for the newlines ("/n") to display properly
<div style={{whiteSpace: "pre-wrap"}}>