Home > Net >  Error: Objects are not valid as a React child (found: object with keys {inputList}). If you meant to
Error: Objects are not valid as a React child (found: object with keys {inputList}). If you meant to

Time:03-11

I was trying object to create input fields using key and value pair. I thought it would be a breeze but I am getting this error. I find no easy way of doing this thing but this.

import {Form, Input, Button } from 'semantic-ui-react'

const input = [{
    name: 'Full Name', 
    dob: 'Date of Birth', 
    parentName: "Father's/Mother's Name", 
    email: "Email",
    mobile: "Mobile Number",
    password: "Password",
    rePassword: "Re-enter Password",
    aadhar: "Aadhar Number"
}]

// const inputList = ["Full Name", "Date of Birth", "Father's/Mother's Name", "Email", "Mobile Number","Password", "Re-enter Password", "Aadhar"]

let inputList = [];

for(let key in input) {
    inputList.push(<Form.Field name={key} key={key} control={Input} label={input[key]} />)
}

const RegistrationForm = () => {
    return(
        <Form>
            <Form.Field name="name" control={Input} placeholder='Full Name' label='Full Name:'/>
            {
                {inputList}
                // inputList.map((input,index) => {
                //     return(<Form.Field key={index} control={Input} label={input}/>)
                // })
            }
        </Form>
    )
}

export default RegistrationForm

So what I am trying to do here is, create an object where my key would be the name of the form field and the value would be the label. To use that I was using for loop but I am getting the above mentioned error. How to resolve this ? If not, is there any other way to get this done.

CodePudding user response:

The problem with your code is that when rendering to the DOM, React will convert JSX to HTML DOM element (you can read more here). So anything inside the curly bracket, React will assume that it is embedded JS code that is expecting to return JSX, an Array of JSX or a value. By doing {{inputList}} what you are trying to do is telling React to render a JS Object with key, ES6 syntax which you can read more here, inputList into the DOM which fundamentally illegal to do so in React. So since you're already do the creation of JSX for each element in inputList in your for loop, you can just do {inputList} instead like this:

const RegistrationForm = () => {
    return(
        <Form>
            <Form.Field name="name" control={Input} placeholder='Full Name' label='Full Name:'/>
            {inputList}
        </Form>
    )
}

On another note, if you don't want to use for loop, what you can do instead is this:

let inputList = Object.entries(input).map(([key, value]) => (<Form.Field name={key} key={key} control={Input} label={value} />));

You can read more on Object.entries here

  • Related