Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda