L Becker
L Becker

Reputation: 755

Retrieving a state value using the string name of the variable in React functional component

I have an array of variable names stored in the state of my functional component - ['firstName', 'lastName', 'userName]. I'm looping over this array to verify that these values are not null in state.

Normally, with a class-based component, I'd be able to use these strings to get their values from state like: this.state['firstName']. But I'm using a functional component that used the useState hook to initialize these values. If I'm looping through my string array, what do I call to get the value from state?

This is sample code to give you an idea of what I'm trying to accomplish:

const MyComponent = (props) => {
   const [ firstName, setFirstName ] = useState(null);
   const [ lastName, setLastName ] = useState(null);
   const [ userName, setUserName ] = useState(null);
   const [ otherField, setOtherField ] = useState(null);

const requiredFields = ['firstName', 'lastName', 'userName'];

const verifyRequiredFields = () => {
   requiredFields.forEach((field) => {
      if (state[field] !== null) { ... } // HERE IS THE PROBLEM - HOW DO I GET STATE?
   }
}
...

Upvotes: 1

Views: 1343

Answers (2)

adel
adel

Reputation: 3507

create one state for the componet which combine the firstName,lastName,userName like this :

const MyComponent = (props) => {
   const [state, setState] = useState({firstName:"",lastName:"",userName:""});
   const [ otherField, setOtherField ] = useState(null);

const requiredFields = ['firstName', 'lastName', 'userName'];

const verifyRequiredFields = () => {
   requiredFields.forEach((field) => {
      if (state[field] !== null) { ... } // HERE IS THE PROBLEM - HOW DO I GET STATE?
   }
}
...

and if you are handling input change for each field you can do it like this now:

const handleChange = (event)=>{
const {name,value} = event.target
setState(current=>({...current,[name]:value}))
}

<input name="firstName" value={state.firstName} onChange={handleChange}/>

Upvotes: 2

yaya
yaya

Reputation: 8243

maybe use eval:

eval(field) // if the value of field is 'firstName',
            // then eval(field) will be the value of firstName.

Upvotes: 1

Related Questions