3

I try to convert an array of objects into a list. For now, I just want to convert a "type" property of my object into a list item, but it doesn't work.

Here is my code:

constructor(props){
    super(props);
    this.travelRawdata = [{type:15}];
}
render(){
    return(
        <ul>
           {this.travelRawdata.forEach(element => <li>{element.type}</li>)}
        </ul>
);}

I don't get any output. If I use console.log(element.type) it works fine, so I think there is something wrong with my HTML tags?

2 Answers 2

6

forEach() will always return undefined. You want to use .map() instead, to convert your data into an array of react elements:

constructor(props){
    super(props);
    this.travelRawdata = [{type:15}];
}
render(){
    return (
        <ul>
           {this.travelRawdata.map(element => <li>{element.type}</li>)}
    </ul>
    );
}

Note: Be sure to read up here on lists and keys. Not including a key for the element, results in rerenders for every single element every time the array is updated.

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried this?

this.travelRawdata.map((item)=> { return (<li>{item.type}</li> })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.