0

I'm working to make my React-Native more dynamic and am building components by mapping an array. Im stuck trying to dynamically assign the prop values because they are already within a bracket.

Is there a way to accomplish this example below? Can I escape the parameter somehow or double bracket the value I need?

// Sample array
fieldArray = [
  {"DefaultValue": "ABCDEF",
   "Name": "Field1"},
  {"DefaultValue": "123456",
   "Name": "Field2"}
]

// Old way having static defined components
<TextInput
  value={this.state.Field1}
  onChangeText={() => {}}
 />
 <TextInput
  value={this.state.Field2}
  onChangeText={() => {}}
 />

What I'd like to do is:

 {fieldArray.map((x) => 
   <TextInput
    value={this.state.{x.Name}}     // <-- This is where I am stuck, can I double bracket in a .map()??
    onChangeText={() => {}}
   /> 
 )}

2 Answers 2

1

In ES 6 you can specify literal like this:

{fieldArray.map((x) => 
  <TextInput
value={this.state[x.Name]}     // <-- This is how you do it
in a .map()??
onChangeText={() => {}}
 /> 
)}
Sign up to request clarification or add additional context in comments.

1 Comment

Im using ES6, but that seems to give me this error: Unexpected token (61:28) right at the first square bracket > 61 | value={this.state.[x.Name]} Did I miss something?
1

Two things you need to take care in your case

  1. The way you are accessing state keys isn’t right. React state is basically an object so to access such keys you can use this.state[keyName] instead of dot notation
  2. You also need to set unique key to TextInput element because it’s rendered in loop otherwise you will always get one TextInput rendered the last one I.e., Field2. Since you don’t have unique id per object in array I would recommend you to use index as key

     {fieldArray.map((x, index) => 
         <TextInput
              key={"Key-"+index}
              value={this.state[x.Name]} 
               onChangeText={() => {}}
         /> 
      )}
    

Comments

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.