I have a component called GameSetup which is basically just a form that user can fill out. Within the GameSetup component I am calling another component called PlayerList which displays a list of players in a html list (list of strings).
On the GameSetup form there is a textbox that allows a user to input a new player name and then click the button to add the user to the game. I have a button click event on the add player button and i update the state which contains an array of strings that contains all of the players (list of strings). When I add a new player I expect the player be displayed from the PlayerList component but it is not re rendering with the correct list it is still at its initails state or it isnt being rerendered.
What do I need to do get the PlayerList component update when a new player is added to the list?
Here is my GameSetup Component:
import React from 'react';
import PlayerList from 'components/playerlist/playerlist';
export default class GameSetup extends React.Component {
constructor(props) {
super(props);
this.state = {localmode: true, players: ["test"], buyIn: 0.00, playerName: ""};
this.handleAddPlayerButtonClick = this.handleAddPlayerButtonClick.bind(this);
this.handlePlayerNameChange = this.handlePlayerNameChange.bind(this);
}
handleAddPlayerButtonClick(event) {
this.setState({
players: this.state.players.push(this.state.playerName)
});
}
handlePlayerNameChange(event) {
this.setState({
playerName: event.target.value
});
}
render() {
return (
<div>
<div className="col-lg-6">
<form>
<h2>General Game Settings</h2>
<hr />
<div className="form-group">
<input type="text" placeholder="Name of Game" className="form-control" />
</div>
<div className="form-group">
<input type="text" placeholder="Buy In" className="form-control" />
</div>
<br/>
<h2>Players</h2>
<hr />
<div className="form-group">
<input type="text" value={this.state.playerName} className="form-control" placeholder="Player Name" onChange={this.handlePlayerNameChange} />
</div>
<button className="btn btn-success" onClick={this.handleAddPlayerButtonClick}>Add Player</button>
<PlayerList players={this.state.players} />
</form>
</div>
<div className="col-lg-6">
<h2>Game Details</h2>
<hr/>
</div>
</div>
);
}
}
Here is my PlayerList component:
import _ from 'lodash';
import React from 'react';
import PlayerListRow from './playerlistrow';
export default class PlayerList extends React.Component {
render() {
var rows = [];
this.props.players.forEach(function(player){
rows.push(<PlayerListRow player={player} key={player.Id} />);
});
return (
<ul>{rows}</ul>
);
}
}
Here is PlayerlistRow component:
import React from 'react';
export default class PlayerListRow extends React.Component {
render() {
return (
<li>{this.props.player}</li>
);
}
}
Here is an example of what the screen looks like:
