Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda