1
import React, { useContext } from 'react'

import styles from './subTheme-select.module.css'
import StoreContext from '../store'

const SUB_THEME = {
  blue: 'Blue',
  yellow: 'Yellow',
  pink: 'Pink',
  purple: 'Purple',
  orange: 'Orange',
  green: 'Green'
}

function SubThemeSelect() {
  const store = useContext(StoreContext)

  return (
    <div className={styles.container}>
      {SUB_THEME.map((subTheme) => (
        <label className={styles.label}>
          <input
            type="radio"
            value={subTheme}
            name={subTheme}
            checked={subTheme === store.subTheme}
            onChange={(e) => store.changeSubTheme(e.target.value)}
          />
          {SUB_THEME[subTheme]}
        </label>
      ))}
    </div>
  )
}

export default SubThemeSelect

I want a use SUB_THEME like an array like [blue, yellow, pink, purple, orange, green] how can I do this.

enter image description here

This is the error message.

How can handle that issue?

Hasan Tezcan
  • 1,116
  • 1
  • 11
  • 23
  • 1
    Does this answer your question? [Get array of object's keys](https://stackoverflow.com/questions/8763125/get-array-of-objects-keys) – Klaycon Jul 29 '20 at 20:41
  • Can you specify if you what the keys for `'blue'` or if you want the values `'Blue'`. Many answers tell you how to get keys but i suspect you want the values. – W-B Jul 29 '20 at 20:56

5 Answers5

2

Since you are trying to map an object you need to use Object.keys which returns an array of the objects keys that you can loop over.

Object.keys(SUB_THEME).map((key,index) => {
 const subTheme = SUB_THEME[key]
 return (
 <label className={styles.label}>
          <input
            type="radio"
            value={subTheme}
            name={subTheme}
            checked={subTheme === store.subTheme}
            onChange={(e) => store.changeSubTheme(e.target.value)}
          />
          {subTheme}
        </label>
  )
})
Omar
  • 3,401
  • 2
  • 23
  • 40
2

You want the Object.keys() function or the Object.values

const SUB_THEME = {
  blue: 'Blue',
  yellow: 'Yellow',
  pink: 'Pink',
  purple: 'Purple',
  orange: 'Orange',
  green: 'Green'
}
//this returns the keys
const theme_keys = Object.keys(SUB_THEME)
//this returns the values
const theme_values = Object.values(SUB_THEME)

Then you can map them like

theme_keys.map( key => {/*code here*/})
theme_values.map( key => {/*code here*/})
W-B
  • 850
  • 5
  • 16
1

You can use as below :

Object.keys(SUB_THEME).map( (key) => {
console.log(SUB_THEME[key]
})
Ganesh chaitanya
  • 638
  • 6
  • 18
0
 Object.keys(SUB_GROUPED).map(x => {
    console.log(x)
 })
Davia
  • 73
  • 10
0

Get object keys firstly with Object.keys(SUB_THEME).

Tarukami
  • 1,160
  • 5
  • 8