Home > Software design >  How to split a long string into a multi-line string, but the string is a value inside of a javascrip
How to split a long string into a multi-line string, but the string is a value inside of a javascrip

Time:03-03

I am creating an FAQ page for a site, and instead of statically typing out every question and answer into each component, I decided to create an array of objects with every question and answer inside of it, and then map through the array to make my react code look cleaner.

Some of the answers are paragraphs, but I want to split up some of the paragraphs into multiple smaller paragraphs.

I've tried \n within backticks and \n within single and double quotes but the paragraph does not split up into multiple lines in the browser. Does it have something to do with being inside of an object and that's why it won't add a new line with \n?

Here is my FAQ object

export const faqData = [{
     question: "Can we make this product personalized?",
     answer: "Yes, all products can be personalized. Please visit our shop page for 
    all personalized options.\n You can view the shop page here."
},

Here is my component

import React from "react";
import Title from "./title/Title";
import Questions from "./faqs/Questions";
import { faqData } from "./utils/faqs";

const FAQ = () => {
  return (
    <div className="Div">
      <Title />
      {faqData.map(({ question, answer }) => (
        <Questions question={question} answer={answer} />
      ))}
    </div>
  );
};

export default FAQ;

CodePudding user response:

Unfortunately we can't see how you're splitting the string in the Questions component with your code shown. It should be a fairly simple mapping on the string.split('\n').

In the return of your Questions component, it should look something similar to:

return (
   <div className="Questions">
      <h2>${props.question}</h2>
      {
         props.answer.split('\n').map((paragraph) => {
            return <p>{paragraph}</p>;
         }
      }
   </div>
)

This will break the answer into an array of strings split up by \n's, then map it into individual paragraph tags.

CodePudding user response:

For a different solution to display multiline instead of \n, you could format your answer in HTML (to use <br />) and use dangerouslySetInnerHTML (Edit angry-haibt-z4u9bg

  • Related