search

Home  >  Q&A  >  body text

I want to create a javascript string so that when it is passed inside a div tag it displays as a list

<p>I'm trying to use JavaScript to display a string containing a list of items in a specific format inside a <code>div</code> tag. The string contains several items that I want to display as a bulleted list. Here is an example string: </p> <pre class="lang-js prettyprint-override"><code>const items = "These are the items:\n1. apple\n2. mango"; </code></pre> <p>I want to format a string so that it appears like this inside a <code>div</code> tag: </p> <pre class="brush:php;toolbar:false;">These are the items: 1. apple 2.mango</pre> <p>I'm using React and Tailwind CSS and this issue is related to React components. </p>
P粉478445671P粉478445671476 days ago635

reply all(2)I'll reply

  • P粉893457026

    P粉8934570262023-09-04 17:19:03

    You can iterate over the mapping method and split it whenever it encounters any "/n". Alternatively, you can create an ordered list for this purpose. For example, find the code below.

    import React from 'react';
        
    const items = "\n1. apple\n2. mango";
    
    const ListComponent = () => {
        const itemList = items.split('\n').map((item, index) => {
            const trimmedItem = item.replace(/^\d+\.\s/, '');
            if (item.trim()) {
              return <li key={index}>{ trimmedItem}</li>;
            }
            return null;
        });
    
        return (
            <div>
                <p>Here is the list:</p>
                <p>These are the items:</p>
                <ol>{itemList}</ol>
            </div>
        );
    };
    
    export default ListComponent;
        
    

    This is a screenshot of the above code running Run the above code

    reply
    0
  • P粉376738875

    P粉3767388752023-09-04 16:57:06

    You should split the string with newlines and then map it to multiple paragraph tags

    const items = "These are the items:\n1. apple\n2. mango";
    
    // or if you want it t be reactive:
    const [items, setItems] = useState("These are the items:\n1. apple\n2. mango");
    

    Then in html:

        <div className="list">
          {items.split('\n').map((el) => (
             <p>{el}</p>
           ))}
        </div>
    

    Now the list displays correctly, if the items are centered and you want them to be left aligned, just enter text-align: left; in the list css class

    reply
    0
  • Cancelreply