0

I am new to React js , in my one component i am setting field name dynamically , it comes from api to redux store then from their it come into my component ,

I want to make one array that i can pass to API in Post method which will have key value pair ,

This is how i am building dynamic fields

        <Panel.Body key={index}>
        {
        this.buildTemplate(item,index)
        }
        </Panel.Body>

In buildTemplate() i am rendering html elements using if else statement and with each element i am using function that can give change state of that field.

 if (['url', 'text', 'title'].indexOf(role) >= 0) {
        return (
            <FormControl  type={role.toLowerCase()} placeholder={role} onChange={this.handleShareholderNameChange(id,item.label)}/>
        )
    } else if (['date'].indexOf(role) >= 0){
        return (
            <DatePicker id="from-date-dt" onChange={this.handleShareholderNameChange(id,item)}/>
        )

In my handleShareholderNameChange

handleShareholderNameChange(id,item){
   var obj={}
   var array= []
   if(obj.id===undefined || obj[fieldName] === undefined){
       obj.id = id;
       obj[fieldName] = evt.target.value;
       array.push(obj);
   }
   if(obj.id === id){
       obj.id = id;
       obj[fieldName]= evt.target.value;
       array.push(obj);
   }
   console.log("array",array);
}

I want each input data with field name like below..

  array = [  { id:1, name:'abc', url:'xyz' },  { id:2, name:'abcd',
 url:'xyz2sqssqsq' }  ]

1 Answer 1

1

It is not possible to dynamicly load in all JSON attributes, the way you build it looks fine. But there always comes a moment that you have to type all the attributes by hand. The most dynamic way to load json objects into a React component is with ReactTable.

Then you can do something like this:

<ReactTable data={[  { id:1, name:'abc', url:'xyz' },  { id:2, name:'abcd',
url:'xyz2sqssqsq' }  ]}
columns={[{"Header": "id", accessor: "id"}, {"Header": "name", accessor: "name"}, {"Header": "url", accessor: "url"}]}
/>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response.. @HarryStylesheet
You're welcome. ReactTable is really helpfull for a quick nice layout for a table. Would you mind marking my answer as the answer? Thanks in advance!

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.