0

I'm trying to use a state as a key for a json in a react project and it's showing up an error, i can't figure out why (i think it's a syntax error with the map function inside {}). Here is the code, i want to use dynamicState inside a map function :


import dataJson from "./data/data.json"

function App() {  
 
  const [dynamicState, setDynamicState] = useState("EN");
  const dataArray = dataJson;

  return ( 
  <div>

    <div className="container">   
      {dataArray.dynamicState.map((estacion, index) => {
        return (
          
          <div className="cardEstacion" key={estacion.id}>
            <h2 class="cardTitle">{estacion.title}</h2>
            <p class="cardSubtitle">{estacion.subTitle}</p>
          </div>
          
        )
      })
      }      
    </div>
    

  </div>
  );
}

here is my data.json file:

{
    "ES": [        
        {
            "id": 0,
            "audio": "",
            "images": [...],
            "title": "",
            "subTitle": "",            
            "body": ""            
        }            
    ],
    "EN" : [
        {
            "id": 0,
            "audio": "",
            "images": [...],
            "title": "",
            "subTitle": "",            
            "body": ""            
        }   
    ]
}

My solution was to convert the data to an array with const dataArray = Object.values(dataJson) and then using it inside the map function with [0] or [1] if i want to reference ES or EN key dataArray[0].map((estacion, index)) but i feel that a dynamic key is a better approach.

Thank you in advance!

tomigeme
  • 15
  • 3
  • You need to use [bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation) for dynamic keys `{dataArray[dynamicState]map(` – pilchard Aug 25 '21 at 22:41
  • Oh, i searched for about 2 hours for that because i didnt wanted to be an ask to ask :facePalm: https://dontasktoask.com/. Thank you x1000 @pilchard – tomigeme Aug 25 '21 at 22:49
  • Heh, no worries! – pilchard Aug 25 '21 at 23:03

0 Answers0