I'm trying to use JavaScript to display a string containing a list of items in a specific format inside a div tag. The string contains several items that I want to display as a bulleted list. Here is an example string:
const items = "These are the items:\n1. apple\n2. mango"; I want to format a string so that it appears like this inside a div tag:
These are the items: 1. apple 2.mango
I'm using React and Tailwind CSS and this issue is related to React components.
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()) { returnHere is the list:
These are the items:
{itemList}
This is a screenshot of the above code runningRun the above code
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:
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