helloWorld
helloWorld

Reputation: 153

React/JSX: Can I use a state variable in another state variable?

I have something like this, where I would like to create array in the state from a variable initialized directly above it. I get the error cards is not defined. Is there a way around this? I need to set this array specifically in the state.

class Example extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      cards: [
        {
          name: "Name 1",
          description: "dfdsfaf",
        },
        {
          name: "Name 2",
          description: "dsfsfasf",
        },
        {
          name: "Name 3",
          description: "daslkdjadlajsd",
        },
     ],
      names: cards.map(item => item.name)
    };
   }
...
}

Upvotes: 2

Views: 861

Answers (1)

hasanain
hasanain

Reputation: 773

You can do this in javascript as follows:

const cards = [...]
const names = = cards.map(...)
this.state = { cards: cards, names: names }

You should probably not do this though and set state to only the cards and move the call to calculate the names to your render method

Upvotes: 5

Related Questions