skip to Main Content

I have a field object created at runtime (via API call) as below

field: {
  "firstNameField-0":
    {
      id: 'firstNameField',
      mandatory: true,
      value: 'First Name 1'
    }
  }

The index (i.e. 0) above is dynamic, but at a time, only one value is possible for the index and I have this value in a state variable "index". So, basically the field names are of the format firstNameField-${index}

I want to pass this field object/configuration to my JSX. So, looking at something like

{
  field.firstNameField &&
    <MyField key={field.firstNameField.id} field={field.firstNameField} />
}

Is it possible to specify and render with this dynamic index in the JSX itself ?

I was trying something like below, but it is throwing syntax error;

<MyField key={field.[`firstNameField-${index}`].id} field={field.[`firstNameField-${index}`]}  />

UPDATED

Is there a shorthand way of writing this JSX, since it is quite verbose and repetitive ?

{
  myContactObj.gridItems &&
  myContactObj.gridItems[index] && 
  myContactObj.gridItems[index].fields[0] && 
  myContactObj.gridItems[index].fields[0][`firstNameField-${index}`] &&
  <MyField key={myContactObj.gridItems[index].fields[0][`firstNameField-${index}`].id} field={myContactObj.gridItems[index].fields[0][`firstNameField-${index}`]} index={index}  />
}

2

Answers


  1. Just remove the dot before the brackets:

    const fieldValue = field[`firstNameField-${index}`];
    <MyField key={fieldValue.id} field={fieldValue}  />
    Login or Signup to reply.
  2. Don’t use dots in bracket notation.

    <MyField key={field[`firstNameField-${index}`].id} field={field[`firstNameField-${index}`]}  />
    

    To shorten nested property checks, you can use optional chaining.

    myContactObj?.gridItems?.[index]?.fields?.[0]?.[`firstNameField-${index}`]
        && <MyField ... />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search