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
Add dynamic key to set state, react

I have this state

this.state = {
   dropdown1: false,
   dropdown2: false,
   dropdown3: false
}

I want to access to these dropdowns in state using this.setState but the number after 'dropdown' comes from API

onMaca = (ev) => {
   this.setState({
       dropdown + ev: true
    })
}

So I want the key to be dynamic 'dropdown1' for example.

Thanks for your answers

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

you can access the object property like this object['property name']

onMaca = (ev) => {
this.state['dropdown' + ev]= true;
   this.setState({
       ...this.state
    })
}
about 4 years ago · Juan Pablo Isaza Report

0

https://codezup.com/add-dynamic-key-to-object-property-in-javascript/

You can use any of these to set key dynamically. I will try to update the answer with an example in a while for setState.

about 4 years ago · Juan Pablo Isaza Report

0

The state is a JS object, so you can get its keys as usual, like so:

const stateKeys = this.state.keys()

Now you have an array: [ "dropdown1", "dropdown1", "dropdown1" ]
One way to use it would be:

const keysMap = statekeys.map(( item, i ) => return { 
  key: item,  
  idx: i,  
  number: item.replace( /dropdown/, '' )  
}  

keysMap will look like so: [ { key: 'dropdown1', idx: 0, number "1" }, { key: 'dropdown1', idx: 1, number "2" }, { key: 'dropdown1', idx: 2, number "3" } ]
You can query keysMap for a given dropDownNumber like so:

let k = keysMap.find( kmap => kmap.key = dropDownNumber )  

To set the dropdown's state:

this.setState({ k: <whatever> })  
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!