doliphin
doliphin

Reputation: 1014

Array not rendering as a collection of children Reactjs

I have a hook, Prompt. one of the props is an Object containing some field names as keys.
I create a form using these fields and some <input>s. This is what the hook Fields returns.
It is rendered from an array. I log this array at log-A. Here is what I get:

y no work

This makes me believe that this is an array of react components.

There is a function that I am trying to make that gets the results of this form.
To do this, I want to go through the children of the <div> with ref={fieldsRef}. Since this just contains a list of react components, I thought I could just get the children of it and use React.Children.toArray().
This does not work.

const Prompt = (props) => {

    //...

    const Fields = () => {
        let fieldKeys = Object.keys(props.fields);
        let fields = [];
        for ( let fieldKey of fieldKeys ) {
            fields.push(
                <div key={fieldKey.toString()}>
                    <div className={"field-name"}>
                        {props.fields[fieldKey]}
                    </div>
                    <input spellCheck="false"/>
                </div>
            );
        }

        console.log(fields); //log-A

        return (
            <div ref={fieldsRef}>
                {fields}
            </div>
        );
    }

    const getForm = () => {
        console.log(fieldsRef); //log-B
        let current = fieldsRef.current.children;
        let children = React.Children.toArray(current);
        return 0;
    }

    //...

}

at log-B, the output is a div. It's current has children that are in a enter image description here.

I get an error when trying to access the children of this.

Uncaught Error: Objects are not valid as a React child (found: [object HTMLDivElement]). If you meant to render a collection of children, use an array instead.

What am I doing wrong, to not be able to access these children and convert to an array using React.Children.toArray(<children>)?

Upvotes: 1

Views: 128

Answers (1)

George F
George F

Reputation: 76

It looks like getForm() is considering {fields} itself to be an object, rather than the array you are trying to reference. Try moving your fields variable declaration into the Prompt() scope instead of the nesting it under Fields().

Also, consider using the React Developer Tools Extension for Chrome, it can really help with debugging issues with props and hooks.

Upvotes: 1

Related Questions