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

218
Visualizações
How can I access a state variable using a string within functional component?

I am trying to access a state variable using a string within a React functional component.

For example, I know in Class components I can do the following to access state based on input:

class Form extends React.Component {

   constructor(props) {
     super(props);
    this.state = {
      inputOne: null
    }}

   handleBlur(e, name) {
       if (!this.state[name]) {
         this.setState({
          [`${name}Missing`]: true,
        });
       } else {
       this.setState({
        [`${name}Missing`]: false,
      });
    }

    render() {
       <input onBlur={(e) => this.handleBlur(e, "inputOne")}></input>
   }
 }

By using this.state[name] within the handleBlur function, I can access the inputOne state value dynamically.

How would I do something similar within a functional component?

Thanks for your time!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The only way to do this in a functional component would be to have the same sort of state structure as in the class component - that is, for the state values you want to dynamically access, put them all into an object (or an array).

const [inputs, setInputs] = useState({
  inputOne: null
})

And then const someStr = 'inputOne' and inputs[someString] will give you that state value. To set it:

setInputs({
  ...inputs,
  [someStr]: newValue
  // or use whatever computed property name you want
});

It's usually recommended to use separate state variables when using functional components - but when you have lots of state variables that you want to dynamically access, using a single object or array can make more sense.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do that:

import { useState } from 'react';

const Custom = () => {
  const [state, setState] = useState({
    inputOne: "",
  });

  const handleBlur = (e, name) => {
    if (!state[name]) {
      setState({
        [`${name}Missing`]: true,
      });
    } else {
      setState({
        [`${name}Missing`]: false,
      });
    }
  }

  return (
    <input onBlur={(e) => handleBlur(e, "inputOne")}></input>
  );
};
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