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

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

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 Denunciar

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 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