How to render children in React?

0

I have the following components:

Obj

import React from 'react';

export default class Obj extends React.Component {
    constructor(props) {
        super(props);
        console.log(props);
    }

    render() {
        let objs = Object.entries(this.props.data)
            .map((keyValue, index) => (
                <p key={index}><b>{keyValue[0]}</b> - {keyValue[1]}</p>
            ));

        console.log(objs);
        return <div>{objs}</div>
    }
}

and Modal:

import React from 'react';

export default class Modal extends React.Component {
    constructor(props) {
        super(props);
    }

    close(e) {
        e.preventDefault();
        e.stopPropagation();
        this.props.onCloseModal();
    }

    render() {
        if (!this.props.isModalOpen) {
            return <div></div>;
        }

        return (
            <div class="modal" style={{ display: "block" }}>
                <div class="modal-content">
                    <div class="modal-header">
                        <span class="close" onClick={e => this.close(e)}>&times;</span>
                        <h2>Details</h2>
                    </div>
                    <div class="modal-body">
                        {this.props.children}
                    </div>
                </div>
            </div>
        );
    }
}

In the parent component they look like this:

render() {
    return (
        <div>
            <Modal
                isModalOpen={this.state.isModalOpen}
                onCloseModal={this.onCloseModal.bind(this)}
            >
                <Obj data={this.state.data} />
            </Modal>
        </div>
    );
}

When the call is made {this.props.children} react complains.

  

Objects are not valid as a React child (found: object with keys ...

Could someone explain what I'm doing wrong?

Thank you.

@edit Sub objects are not understood by the react they need to be handled for Nodes.

    
asked by anonymous 20.03.2017 / 14:14

2 answers

3

The children props object is not a collection of nodes of Virtual DOM , so it can not print them. The problem is that I did not quite understand what you were trying to do ...

    
20.03.2017 / 15:03
-1

Try it like this ... I have not tested ...

Put the loop map inside the div in JSX

Obj

import React from 'react';

export default class Obj extends React.Component {
    constructor(props) {
        super(props);
        console.log(props);
    }

    render() {
        return (
            <div>
                { Object.entries(this.props.data).map((keyValue, index) => 
                  (<p key={index}><b>{keyValue[0]}</b> - {keyValue[1]}</p>)
                ) }
            </div>
       )
    }
}
    
08.06.2018 / 12:52