Home > Mobile >  What is the right way to pass array of objects to a form component of react?
What is the right way to pass array of objects to a form component of react?

Time:07-15

I have a data.js file with the following data

const formData = [
    {
     name: 'username',
     type: 'text',
     placeholder: 'placeholder',
     labelText: 'User Name'
},

{
     name: 'password',
     type: 'password',
     placeholder:'password',
     labelText: 'Password'
  }
]

export {formData}
    

This data.js file sits in a data folder within the main directory.

I am adding a form component in loginForm.ts with the following data

import { NextPage } from "next";

export interface FormProps {
        name: string;
        type: string;
        placeholder: string;
        labelText: string;
    }


const loginForm: NextPage<FormProps> = ({name, type, placeholder, labelText}) => {
    return (
       <div>
         <label>{labelText}</label>
         <input
            name = {name} 
            type = {type}
            placeholder = {placeholder}
         />
       </div>
   )
}

export default loginForm;

Finally, in LoginView.ts (in another folder), I am importing loginForm and data.js and mapping the values to the loginForm from data.js

import loginForm from '../source/loginForm';
import formData from '..source/data';

const fields = formData;
const Login: NextPage = () => {
    return (
        <div className="container">
            {
                fields.map((field => 
                        <loginForm key={field.name} {...field}/>
                    )
                )
            }
        </div>
    );
}

But I get an error - Property 'map' does not exist on type 'NextPage<FormProps, FormProps>'. Can anyone explain why it happens and the solution?

Thanks

CodePudding user response:

In your data.js file you are exporting formData as a named export rather than a default export. So you just need to change your import.

import { formData } from '..source/data';

If you want to keep it as you have it then you need to include a default export like you are doing in your loginForm component.

  • Related