0

So I'm new to React and I'm trying to dynamically set the state of a card to "selected" or not. I have the click event working from child -> parent. However, when it gets into the parent I can't seem to get it to be assigned to state dynamically (because I may not know how many cards there are I obviously don't want to hard code this).

Here is my method:

handleCardClick(card) {
    let title = card.title;

    this.setState((preState, props) => ({
        title: true
    }));

    console.log('card: ', this.state);
}

I am aware that I'm not using the preState and props yet, but I will need them later.

How can I make the state hold the actual title and not the literal string "title"?

So instead of {title: true} it would be something like {some_title: true}

I am also getting a warning in VS Code the title is assigned but never used. I this not the best way to do this? Obviously, I don't want this warning every I do something like this.

ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
Garrett
  • 1,576
  • 4
  • 27
  • 51
  • Possible duplicate of [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – maazadeeb May 13 '19 at 10:55
  • @MaazSyedAdeeb Please see updated question – Garrett May 13 '19 at 10:56
  • You can use bracket notation to set property from variable like this this.setState((preState, props) => ({ [card.title]: true })); – R.K.Saini May 13 '19 at 10:58

2 Answers2

1

You can use bracket notation to set dynamic key,

Also, use arrow functions in class properties to avoid binding this.handleCardClick = this.handleCardClick.bind(this).

handleCardClick = ({ title }) => {       // <-- No binding required.
    this.setState((preState, props) => ({
        [title]: true                    // Dynamic key
    }));
}

and in your ParentCard:

cardAction = () => {
  if (this.state.myCard1 === true) {
     // ... do some action
  {
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

You can use bracket notation to set property from variable like this

handleCardClick(card) {

    this.setState((preState, props) => ({
        [card.title]: true
    }));
}
R.K.Saini
  • 2,678
  • 1
  • 18
  • 25