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
Answer
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM