Search code examples
javascriptreactjsredux-formreact-redux-form

How to have React evaluate a dynamic variable?


I have the following:

    {this.props.fields.map(field => (
      <div key={field.skill_id}>
        <Field
          component={RadioGroup}
          name={ 'skill_id_' + field.skill_id }
          title={field.name}
          activeValue={this.props.formState && this.props.formState.skill_id_${field.skill_id}}
          required={true}
          options={[
            { title: '1', value: '1' },
            { title: '2', value: '2' },
            { title: '3', value: '3' },
            { title: '4', value: '4' },
            { title: '5', value: '5' }
        ]} />

      </div>
    ))}

activeValue is not being evaluated correctly. I need this variable to be dynamically evaluated:

this.props.formState.skill_id_${field.skill_id}}

What am I doing wrong?

I get

syntax error: Unexpected token, expected } (57:82) 55
name={ 'skill_id_' + field.skill_id } 56
title={field.name} > 57
activeValue={this.props.formState && this.props.formState.skill_id_${field.skill_id}}


Solution

  • You are using a dynamic key to the get the value from object so use [] notation.

    Write it like this:

    activeValue={this.props.formState && 
      this.props.formState[`skill_id_${field.skill_id}`]}
    

    Check this Snippet:

    let obj = {
       a1: 1,
       a2: 2,
       a3: 3
    };
    
    [1,2,3].forEach(i => {
    
       console.log(`a${i} = `, obj[`a${i}`]);
       
    })

    Check the MDN doc for more details about template literals.

    Check this answer for more details about bracket notation.