T. Jony
T. Jony

Reputation: 71

Right way to manage components functionality in React

I found on React documentation page, that the technique using the right way React can be based on Single responsibility principle, that is a component should do one thing only. I've already made a simple Gameboard, which includes input, score random generated number and a condition. All the calculations and presentations are made in Gameboard component. Now I would like split up my application in to different components. What is the proper way to do so? One way as I thought is to make a different components like so: Score, Input, RandomNumber. But I'm pretty lost. I make a Score component, in that component I'm displaying data and updating the score state. So how should I pass this data to my parent Gameboard component? With a callback function?

Or should I just make a variable in Gameboard of my score value, all the incrementation(functionality of score: this.state.score + 1 should be done in Score component, update the score in Score component and send the updated data to Gameboard component?

Upvotes: 1

Views: 97

Answers (1)

TKoL
TKoL

Reputation: 13892

Here's an extremely simple example where the state of the score is stored in the Gameboard, but is to be displayed and possibly added to by the Scoreboard

class Gameboard extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      score: 1
    }
  }
  
  add() {
    const newScore = this.state.score + 1;
    this.setState({score:newScore});
  }
  
  render() {
    return (
        <div>
          <Scoreboard score={this.state.score} onAdd={this.add.bind(this)}/>
        </div>
    )
  }
}

class Scoreboard extends React.Component {
  render() {
    return (
      <header>
        <h1>{this.props.score}</h1>
        <button onClick={this.props.onAdd}>add</button>
      </header>
    )
  }
}

ReactDOM.render(<Gameboard />, mountNode);

You can input that code into this site to see it work.

Upvotes: 1

Related Questions