Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
React - use setField pattern with a dynamically set key

I'm attempting to create a component that dynamically renders a number of inputs for a supplied number of languages. This works, but I'm having trouble making this component re-usable by making the attribute that gets updated dynamic.

type Props = {
  formState: [any, any];
  id: string;
  attribute: string;
  languages: string[];
  value: TranslatableString;
};

const TranslatableFieldInput = (props: Props) => {
  const intl = useIntl();
  const [fields, setFields] = props.formState;
  return <> {props.languages.map((language: string) => (

  <Input
    id={props.id + language}
    name={props.attribute + '-' + language}
    type="text"
    label={intl.formatMessage({ id: ("general.languages." + language) })}
    onChange={e => {
      let value = fields[props.attribute]
      value[language] = e.target.value;
      setFields({fields, attribute: value});
    }}
    value={props.value[language]}
    required
    key={props.id + language}
  />
  ))
}
</>
};

export default TranslatableFieldInput;

My problem comes with setFields({fields, attribute: value});. This has the attribute key hard coded. I would like to take whatever the props.attribute string value is, and use this as the key. For example if props.attribute is "name", then the code would evaluate to setFields({fields, name: value});

I've tried searching for methods such as setKey or something equivalent but with no joy. How can I accomplish the above?

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use computed property names: { [name_expression]: value_expression }

<Input
  onChange={e => {
    let value = fields[props.attribute]
    value[language] = e.target.value;
    setFields({ ...fields, [props.attribute]: value });
  }}
  />
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!