Home > front end >  How to render values from object with arrays in react typescript
How to render values from object with arrays in react typescript

Time:03-03

Hey everyone I am trying to render a few values inside an object with arrays but have a hard to doing so. Here is an example of the object:

test { 
  arr1: [{alert: "this is alert 1", passed: true}], 
  arr2: [{alert: "this is alert 2", passed: false}], 
  arr3: [{alert: "this is alert 3", passed: true}]
} 

So basically I want to render the alert and passed values. I tried using Object.keys and then inside mapping individual array based on the key but no luck.

Edit: Sorry if I my question wasn't clear but I was able to resolve it. Here is the code for anyone curious.

Object.keys(this.state.test).map((name, I) => (
  this.state.test[name].map((tmp, idx) => (
    <li key={idx}>{tmp.alert}</li>
    <li key={idx}>{tmp.passed}</li>
  ))
))

CodePudding user response:

The object is called Object, not Objects. Any browser console or build process would be telling you that Objects is not defined.

Additionally, you can't have multiple JSX nodes that aren't surrounded by a parent node. So that's a syntax error in the callback passed to .map(). Which should also be evident as a console error or build error, depending on how you run your application.

Either way, these errors are being reported to you somewhere. If you're not seeing them then now is a good time to take a step back and better understand your development process, because seeing error messages when things fail is critical.

Once these two things are corrected, your logic works just fine:

Object.keys(this.state.test).map((name, I) => (
  this.state.test[name].map((tmp, idx) => (
    <>
      <li key={idx}>{tmp.alert}</li>
      <li key={idx}>{tmp.passed}</li>
    </>
  ))
))

Though you may want to re-think your approach a bit, because using the same key value for multiple nodes isn't going to make React happy. It's unlikely to cause any immediate problems, though may produce warnings/errors in the browser console. But you'd be better off changing the markup a bit to just use a single <li> and modify how you're displaying the two values within that element.

CodePudding user response:

useState triggers a re-render only if the element inside is changed, not mutated. Therefore you have to have seperate booleans or make a shallow copy and pass it to the setState.

Ex: setArr1(s => s.map(el => ({...el, passed: true})))

If your state is like above, you should destructure it.

If that's your question. I have to agree on what super said.

  • Related