1

I am trying to concatenate a string to shape an object, like this:

{addInput.inputs.map((input, index) => (
  <FormField
    key={input}
    label="Entreprenuer Name*"
    controlId={`entreprenuerName-${index}`}
    onChange={e => {
      startupFourthStepFormActionHandler({ `entreprenuerName-${index}`: e.target.value });
    }}
    value={startupFourthStepForm.entreprenuerName}
  />
))}

But I am getting a Failed To Compiled error and Property assignment expected on this line:

onChange={e => {
      startupFourthStepFormActionHandler({ `entreprenuerName-${index}`: e.target.value })
};

All I want is to add the index to the entreprenuerName- key on the object.

What am I missing?

Reacting
  • 5,543
  • 7
  • 35
  • 86

2 Answers2

2

Computed object keys need to be wrapped in []. Try this:

  startupFourthStepFormActionHandler({ [`entreprenuerName-${index}`]: e.target.value });
Danny Delott
  • 6,756
  • 3
  • 33
  • 57
1

You need to wrap the template literal inside brackets [...] for what you are trying to do. This is the way to use computed property names, example:

let index = 1;

const obj = {
   [`entreprenuerName-${index}`]: "some_value"
};

index = 2;
obj[`entreprenuerName-${index}`] = "some_other_value";

console.log(obj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Or, in your particular case, change the code to this:

{addInput.inputs.map((input, index) => (
    <FormField
        key={input}
        label="Entreprenuer Name*"
        controlId={`entreprenuerName-${index}`}
        onChange={e => {
            startupFourthStepFormActionHandler({
                [`entreprenuerName-${index}`]: e.target.value
            });
        }}
        value={startupFourthStepForm.entreprenuerName}
    />
))}
Shidersz
  • 16,846
  • 2
  • 23
  • 48