Im trying to create a sidebar using react. This sidebar will feature the title of a post, followed by a list of headings and subheading (in the format [header] [sub-headers], [header2] [sub-headers2] etc...). The data is in the form of a dictionary. However I cant find how to use the map function to iterate over the specific key in the dictionary.
Here is what i have:
import React, {useState} from 'react'
import {DUMMY_POSTS} from '../data'
import Thumbnail1 from '../images/1.png'
const DUMMY_POST = [
{
id: '1',
thumbnail: Thumbnail1,
category:'NPO',
title:'1971',
headers:['Logo','Colors','Typography','Graphical Elements','Applications'],
sub_headers:[[''],
['Main Colors','Space Neutrals','Heading'],
[''],
[''],
['Postcards','Accreditations','Ticket Packaging','Event Schedule']],
}]
const PostDetail = () => {
const [postDetails,setPostDetails] = useState(DUMMY_POST)
return (
<section className='PostDetails'>
<div className="details__sidebar">
{postDetails.map(({id,title}) => {
return <div className="details__sidebar__container">
<div className='details__sidebar__title'>
<h3>{title}</h3>
</div>
</div> })}
{postDetails.map(({headers,sub_headers}, index) => {
return<div className="details__sidebar__headers" key = {index}>
<ul><h4>{headers[index]}</h4> </ul>
<div className="details__sidebar__sub-headers">
<p>{sub_headers[index]}</p>
</div>
</div>
})}
<div className='Post__Details'>
Post Details
</div>
</div>
</section>
)
}
export default PostDetail
However, this creates a list of only the first header and the first sub_header array
In summary, here is what im trying to do in pseudocode:
Create an h3 element containing the postDetail's title
For each header in postDetail's headers:
Create a div with key as the index
Create an h4 element containing the current header
If the length of the corresponding sub_headers array is greater than 0:
Create a ul element
For each subHeader in the corresponding sub_headers array:
Create an li element containing the current subHeader
where the final outcome should look something like this:sidebar image
i wrote out a return statement based on your psuedocode. the main takeaway here is that i have a map function nested in the postDetail's map function to iterate through the headers. your second map call is iterating through the postDetails array and using the index from that array, not from the headers array. since postDetails length is 1, it doesn't matter how many headers you have, the index is not from the header array.