1

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!

1
  • This is too broad a question. Get some real code and try to do on something in codesandbox. Read up useState. Commented Oct 13, 2021 at 18:00

2 Answers 2

1

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>
  );
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Ali! This answer most closely resembles the structure of my app. Appreciate your time!
1

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.

1 Comment

Thanks so much, definitely learned something new here!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.