Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!