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.

3
  • Possible duplicate of React setState not updating state Commented May 13, 2019 at 10:55
  • @MaazSyedAdeeb Please see updated question Commented May 13, 2019 at 10:56
  • You can use bracket notation to set property from variable like this this.setState((preState, props) => ({ [card.title]: true })); Commented May 13, 2019 at 10:58

2 Answers 2

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

Comments

0

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

handleCardClick(card) {

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

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.