JavaScript React Components Managing State and Data Flow Adding Items to State

miguel soriano
miguel soriano
2,177 Points

my code is not working, can you let me know where I am wrong?

My code does not add the player that is typed on the form. this is my code in App. js: import React, {Component} from 'react'; import Header from './Header'; import Player from './Player'; import AddPlayerForm from './AddPlayerForm';

class App extends Component { state = { players: [ { name: "Guil", id: 1, score: 0,

  },
  {
    name: "Treasure",
    id: 2,
    score: 0,

  },
  {
    name: "Ashley",
    id: 3,
    score: 0,

  },
  {
    name: "James",
    id: 4,
    score: 0, 

  }
],

}; //player id counter prevPlayerID = 4 ;

handleRemovePlayer = (id) => { this.setState( prevState => { return { players: prevState.players.filter(p => p.id !== id) }; }); }

handleScoreChange = (index, change) => { this.setState( prevState => ({ score: prevState.players[index].score += change })); }

handleAddPlayer = (name) => {
  this.setState({
    players: [
      ...this.state.players,
      {
        name: name,
        score: 0,
        id: this.prevPlayerID += 1,
      }
    ]
  });
}

render() { return ( <div className="scoreboard"> <Header title="Scoreboard" players = {this.state.players} />

    {/* Players list */}
    {this.state.players.map( (player,index) =>
      <Player 
        name={player.name}
        id={player.id}
        key={player.id.toString()}
        index = {index}
        changeScore={this.handleScoreChange}
        removePlayer={this.handleRemovePlayer}
        score={player.score}       
      />
    )}
    <AddPlayerForm addPlayer = {this.handleAddPlayer}/>
  </div>
);

} }

export default App;

---------------------------------and this is my code in AddPlayerForm.js :

import React,{Component} from 'react';

class AddPlayerForm extends Component { state = { value: "", }

handleValueChange = (event) => {
    this.setState({
        value:event.target.value
    }
    )
}

handleSubmit = (e) => {
e.preventdefault();
this.props.addPlayer(this.state.value);
}

render(){
    return (
        <form onSubmit = {this.handleSubmit}>
            <input 
            type = "text"
            value = {this.state.value}
            onChange = {this.handleValueChange}
            placeholder = "Enter a player's name"
            />

            <input
            type = "submit"
            value = "Add Player"
            />
        </form>
    );

}

} export default AddPlayerForm;

miguel soriano
miguel soriano
2,177 Points

Sorry, already saw the problem. My e.preventDefault() was e.preventdefault()

Steph Lienti
Steph Lienti
8,046 Points

Thank you ...this helped me as I did the same thing! Reviewing line after line of code for four days....I had e.PreventDefault().

Thank you Miguel!