I am working with React + JS in an app to render news of the NYTimes (https://developer.nytimes.com/). Well, the matter is that I want to render the most viewed in the last 7 days, but organized through categories or sections. And I have the problem with the rendering of my sections.
Here my app.js component:
import React, {useEffect, useState} from "react";
import ListOfSections from "./components/ListOfSections";
import getSections from "./services/getSections";
import Navbar from "./shared/Navbar/Navbar";
function App() {
const [section, setSection] = useState([]);
useEffect(() => {
getSections().then(sections=>setSection(sections));
}, [])
return (
<div>
<Navbar/>
<ListOfSections section={section}></ListOfSections>
</div>
);
}
export default App;
Here my ListOfSections component:
import React from 'react';
import Section from './Section';
export default function ListOfSections ({section}) {
return (
<div className="container_list_sections mt-4 ml-4">
{
section.map(({section})=>
<Section
section={section}
/>
)
}
</div>
)
};
And here my Section component:
import React from 'react';
export default function Section ({section}) {
return (
<div>
<h1 className="section-container mr-4">{section}</h1>
</div>
)
};
Well, the problem is when I do console.log(section) in the Section component, it returns me undefined. But if I do console.log(section) in ListOfSections component, it has received the information of the props. So... why when I am passing the prop section from ListOfSections to Section, is it undefined? Where is it the error? I dont understand. The result for the moment is this one:
Thanks :)
Your useEffect should look as follows:
const [sections, setSections] = useState([]);
...
useEffect(() => {
getSections().then(sections=>setSections(sections));
}, [])
When you get data back it seems to be an array of sections so it should be a plural.
So when you pass sections down as a prop, it should be:
<ListOfSections sections={sections}/>
Which then allows you to map in <ListOfSections>
export default function ListOfSections ({sections}) {
return (
<div className="container_list_sections mt-4 ml-4">
{
sections.map(section =>
<Section
section={section}
/>
)
}
</div>
)
};
For maps, you should also set a key, you can read more here