I have the following data structure:
const bullets = [
"Top Sports are:",
"hockey",
"soccer",
"football",
"Top Names are:",
"liam",
"noah",
"jordan"
]
I am able to make a bulleted list using MUI’s typography comoponent like so:
import { Typography } from 'components/Typography'
//...
<div >
{bullets.map((bullet: string, index: any) => (
<Typography key={index} component='li' variant='body2'>
{bullet}
</Typography>
)
)}
</div>
However, I would like to change the data structure to have arrays for the nested/indented lists like so:
const nestedBullets = [
"Top Sports are:",
["hockey","soccer","football"],
"Top Names are:",
["liam","noah","jordan"]
]
But I don’t know how to adapt the original code to deal with the nested lists so they appear like this rather than a flat bulleted list:
- Top Sports are:
- hockey
- soccer
- football
- Top Names are:
- liam
- noah
- jordan
2
Answers
one solution I can think of is to create a component that accepts an array of items as props and then display it with the
map()
method, for each iteration checks if the item is an array so it recursively calls itself otherwise directly display it:I think the problem with @Ahmed Sbai’s answer is that it does not include the usage of Mui Typography as per the question but it’s on the right path.
Here is my solution… I’ve written in typescript so replace it with JS if required. This also accounts for nesting multiple levels dictated by the data structure passed in for "infinite" nesting.
Displays as like the following, apply your own styles 🙂.
Renders:
"Infinite" nesting levels:
Note: The
ListCoponent
expects anArray
to be passed for theitems
prop.