Home > other >  React - use setField pattern with a dynamically set key
React - use setField pattern with a dynamically set key

Time:12-07

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.

CodePudding user response:

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 });
  }}
  />
  • Related