0

trying to add new line when display values in react.
Can somebody tell me what am I missing?
here is my code

const qList = qs.map(
    (question, idx) => (<div key={idx}>{idx>0?<hr />:<span />}{idx+1 + '. ' + 
    question.split('\n').map((item) => {return (item);})}</div>)
  );

  return (
    <div style={{ width: '100%' }}>
      { qList }
    </div>
  );

question data:
this is line first line.\nThe second\n and this is third

expected result:
this is line first line.
The second
and this is third

What I get:
this is line first line.,The second, and this is third

reference

UPDATED ANSWER:

const qList = qs.map((question, idx) => (
        <div key={idx}>
          {idx>0?<hr />:<span />}
          {<span>
            {idx+1 + '. '}
          </span>}
          {
            question.split('\n').map(item =>(
              <span>
                {item}
                <br />
              </span>
            ))
          }
        </div>
      ));

return (
    <div style={{ width: '100%' }}>
      { qList }
    </div>
  );

2 Answers 2

1
class Application extends React.Component {
render() {
  let qlist = ["this is line first line.\nThe second\n and this is third"];
  return (
    <div style={{ width: '100%' }}>
      { 
        qlist.map((qs, idx) => (
          <div key={idx}>
            {
              qs.split("\n").map(item => (
                <span>
                  {item}
                  <br/>
                </span>
              ))
            }
          </div>
         ))
      }
    </div>
  );
}
}
Sign up to request clarification or add additional context in comments.

Comments

0

HTML does not understand \n. Use <br /> instead.

This should help:

question.split('\n').map((item) => {return <span> {item} + <br /></span>;})}</div>)

2 Comments

I tried that also, but no luck.can you update with a code example?
thanks for the help. but it's not working. giving <br /> instead of new line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.