I'm new to React and programing in general and I'm having trouble writing code that return each element in an array, in React JS. the whole code is below:
import React from 'react'
const App = () => {
const course = {
name: 'Half Stack application development',
parts: [
{
name: 'Fundamentals of React',
exercises: 10
},
{
name: 'Using props to pass data',
exercises: 7
},
{
name: 'State of a component',
exercises: 14
}
]
}
const Header = (props) => {
return (
<h1>{props.course.name}</h1>
)
}
const Content = (props) => {
const lisItem = props.course.parts.map((part =>
<li>{props.course.parts.name}</li>
))
return (
<ul>{lisItem}</ul>
)
}
return (
<div>
<Header course={course}/>
<Content course={course}/>
</div>
)
}
export default App
Right now it half-works: I can display 3 bullet points (match with numbers of parts
) but cannot display the name of the part itself.
Also I would like to clarify the out put a wanted is the course's name
and each name
of the parts
be displayed.
Any help would be appreciated. Thank you very much.
CodePudding user response:
You are not using map
correctly. It should be like this:
const lisItem = props.course.parts.map((part) => <li>{part.name}</li>);
You were ignoring each part
given to you by map
. Check docs of map
.
Also I see now you were defining the two components Header
and Content
inside the App component, that is not good practice (due to reconciliation), move their definition outside of App
:
import React from "react";
const Header = (props) => {
return <h1>{props.course.name}</h1>;
};
const Content = (props) => {
const lisItem = props.course.parts.map((part) => <li>{part.name}</li>);
return <ul>{lisItem}</ul>;
};
const App = () => {
const course = {
name: "Half Stack application development",
parts: [
{
name: "Fundamentals of React",
exercises: 10,
},
{
name: "Using props to pass data",
exercises: 7,
},
{
name: "State of a component",
exercises: 14,
},
],
};
return (
<div>
<Header course={course} />
<Content course={course} />
</div>
);
};
CodePudding user response:
Your .map( part => ...)
iterates props.course.parts
, the part inside the map function is a single item of the list.
Check MDN for more info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map