Pasteque
Pasteque

Reputation: 107

REACT: Use setState in a function called from another component?

I'm starting in ReactJS and I'm doing a score system for my game in React.

I used a component called Score to manage it.

I did a score value in the state that can be incremented by increment().

The problem is that I would like to use this function from my App component (it's an example, I created incrementScore() to show it).

However my increment() can't gain access to this.setState() when the function is called from another component.

Note that I created a button "Increment" inside Score.js which uses increment() and it's works perfectly.

Have you a solution or could you just give a clue? Thanks!

App.js:

import Score from './Score'

class App extends React.Component {

  incrementScore() {
    Score.prototype.increment()
  }

  render() {
    return (
        <div>
          <h1 id="title">Game</h1>
          <Score />
          <Canvas /> {/*Not important here, just for the game*/}
        </div>
    )
  }
}

export default App

Score.js:

import React from 'react'

class Score extends React.Component {

  constructor() {
    super()
    this.state = {
      score: 0
    }
    this.increment = this.increment.bind(this)
  }

  increment() {
    this.setState({
      score: this.state.score + 1 //this.state.score + 1
    })
  }

  render() {
    return (
      <div>
        <p id="score">Score: {this.state.score}</p>
        <button>Incrementer</button>
      </div>
    )
  }
}

export default

Upvotes: 1

Views: 3491

Answers (1)

dev
dev

Reputation: 893

As mentioned by Robin, just move your state to your parent App component, and let your Score component be a 'stateless' component. Also, make sure to pass the increment function down as a prop and use that within your button as an onClick function.

class App extends React.Component {
constructor() {
    super()
    this.state = {
      score: 0
    }
    this.increment = this.increment.bind(this)
  }

  increment() {
    this.setState({
      score: this.state.score + 1 //this.state.score + 1
    })
  }

  render() {
    return (
      <div>
        <h1 id="title">Game</h1>
        <Score scoreCount={this.state.score} increment={this.increment}/>
      </div>
    )
  }
}
const Score = props =>
      <div>
        <p id="score">Score: {props.scoreCount}</p>
        <button onClick={props.increment}>Incrementer</button>
      </div>

See a live example here: https://codesandbox.io/s/wq4kqqz0mw

Upvotes: 2

Related Questions