1

I'm able to map data when just using an object, but when using an array it doesn't some to work.

No errors in command line just nothing outputted.

Help appreciated.

Thanks

import React from 'react';
import ReactDOM from 'react-dom';

class JoeApp extends React.Component {
    render() {
        var data = [
            {
                name: "Joe",
                age: 27
            },
            {
                name: "John",
                age: 27
            },
            {
                name: "Bill",
                age: 25
            }
        ];

        return (
            <Data data={data} />
        );
    }
}

class Data extends React.Component {
    render() {
        return (
            <div>{this.props.data.name.map((info) => info.name})}</div>
        );
    }
}

ReactDOM.render(<JoeApp />, document.body);

1 Answer 1

4

You need to use the .map() function on the array itself, which would be this.props.data:

<div>{this.props.data.map((elem) => elem.name})}</div>

This will convert the array of objects:

var data = [
        {
            name: "Joe",
            age: 27
        },
        {
            name: "John",
            age: 27
        },
        {
            name: "Bill",
            age: 25
        }
    ];

To an array of name strings:

var data = ["Joe", "John", "Bill"];
Sign up to request clarification or add additional context in comments.

1 Comment

there's an useless curly bracket in <div>{this.props.data.map((elem) => elem.name)}</div>

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.