bafix2203
bafix2203

Reputation: 541

Update item in state onClick ReactJS

So, I have class Comopnent :

 state = {
    tokens: [
    {
      name: "first",
      value: 3
    },
    {
      name: "second",
      value: 2
    },
    {
      name: "third",
      value: 4
    }
  ]
  }
  handleClick = (name, id) => {
    const newState = this.state.tokens.map((token => {
    console.log(token.name)
    }))
  }
render() {
    const token = this.state.tokens;

    const tokenList = token.map(t => {
      return (
      <div value={t.name} onClick={() => this.handleClick(t.name, t.value)}>
        <img src=""/>

        </div>
      )
    })

What i need to do - after click - to subtract 1 from value clicked token. So - ex. after click on "First" token i want his value equal 2. So far I've done just as much as the above. I do not know how to go about it, i am new in ReactJS, so thanks for help in advance!

Upvotes: 1

Views: 47

Answers (2)

Miguel Angel
Miguel Angel

Reputation: 983

First, some things are wrong with your code. 1- You have an array of tokens, then you're mapping the list, but you don't have a key to index, this will cause weird behaviors, I improve your tokens list with keys now.

2.- You can handle the click and change the state of the tokens list, this will trigger a reload of the component.

state = {
    tokens: [
    {
      name: "first",
      value: 3,
      id: 1
    },
    {
      name: "second",
      value: 2,
      id: 2
    },
    {
      name: "third",
      value: 4,
      id: 3
    }
  ]
  }
  handleClick = (name, id) => {
        const { tokens} = this.state;
        const newState = tokens.map((token => {
                if(token.id === id) {
                        token.value--;

                }
        return token;
    }))
  }
render() {
    const token = this.state.tokens;

    const tokenList = token.map(t => {
      return (
      <div key={t.key} value={t.name} onClick={() => this.handleClick(t.name, t.value, t.key)}>
        <img src=""/>

        </div>
      )
    })

Upvotes: 1

kind user
kind user

Reputation: 41893

You'll have to find in your state in tokens array the object which has the same name as the argument passed in the onclick handler. Then you will have to change it's value - decrement it (value--) but you have to be aware that you can't mutate the state.

 handleClick = name => () => {
    const { tokens } = this.state;
    const clickedToken = tokens.find(token => token.name === name);
    clickedToken.value--;
    const clickedTokenIndex = tokens.indexOf(clickedToken);
    const newTokens = [
      ...tokens.slice(0, clickedTokenIndex),
      clickedToken,
      ...tokens.slice(clickedTokenIndex + 1)
    ];

    this.setState({ tokens: newTokens });
  };

Codesandbox link: https://codesandbox.io/s/92yz34x97w

Upvotes: 1

Related Questions