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?

2
  • 1
    Does this answer your question? Get array of object's keys Commented Jul 29, 2020 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. Commented Jul 29, 2020 at 20:56

5 Answers 5

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

Comments

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>
  )
})

Comments

1

You can use as below :

Object.keys(SUB_THEME).map( (key) => {
console.log(SUB_THEME[key]
})

Comments

0
 Object.keys(SUB_GROUPED).map(x => {
    console.log(x)
 })

Comments

0

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

Comments

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.