Reputation: 1321
I have a problem with my component, I need to render list of skills-elements from array in export.data. I think, that I missed some arguments in my map:
const React = require('react')
class Post extends React.Component {
render () {
const { route } = this.props
const post = route.page.data
return this.props.route.page.data.skills.map(() => (
<div>
<h1>{this.props.route.page.data.title}</h1>
<ul>
<li>{this.props.route.page.data.skills}</li>
</ul>
</div>
)
)
}
}
Post.propTypes = {
route: React.PropTypes.object,
}
export default Post
exports.data = {
title: 'Tech Skills',
skills: ['One skill', 'Two skill'],
}
Upvotes: 0
Views: 2822
Reputation: 768
You need to recieve the skill
inside your map, since your map function will recieve each element of the array.
You can get the information of each element in the skill object that the map recieves.
Also, with your code, beware that you will be showing the <h1>
title for each element that you are printing. You should do something like this:
return (
<div>
<h1>{this.props.route.page.data.title}</h1>
<ul>
{
this.props.route.page.data.skills.map((skill) => {
return <li key={skill.id}>{skill}</li>
})
}
</ul>
</div>
)
Here, you will only show the title once, and afterwards you will create a element of the list of each skill. Also remember that the key
parameter is needed if you are creating JSX elements inside a map or any iterating function, since React uses this key to better optimize the re-rendering of the component
Hope it helps!
Upvotes: 1
Reputation: 9680
The callback in map
function received the iterated element as its argument. Also, your render
function should return a single container, which contains the list of elements. So you need to do something like this:
return (
<div>
{this.props.route.page.data.skills.map((skill) => (
<div key={skill}>
<h1>{this.props.route.page.data.title}</h1>
<ul>
<li>{skill}</li>
</ul>
</div>
))}
</div>)
Note also that you need to give each <div>
a key
attribute to avoid errors in react.
Upvotes: 1
Reputation: 104359
Reason is, you are returning more than one element from render method (an array). We can't return multiple elements so wrap them inside a div
.
Don't forget that the render()
is basically a function
, Functions always take in a number of parameters and always return exactly one value.
Like this:
render () {
const { route } = this.props;
const post = route.page.data;
return <div>
{this.props.route.page.data.skills.map(el => (
<div>
...
</div>
))}
</div>
)
}
Inside the map
body el
will be each object
of the array, to access any value use el.keyName
.
Upvotes: 1