I'm new to react and only understand the basic. I got this project from someone to look at, but I'm scratching my head since morning on how the deletePersonHandler function works and how is he passing index as a prop and then accessing that prop in the Person component, and by clicking on a component he can delete the specific component. Please if you can try to try to go over it in easy but in under the hood way.Your help would be really appreciated.
App Component
class App extends Component {
state = {
persons: [
{ id: 'asfa1', name: 'Max', age: 28 },
{ id: 'vasdf1', name: 'Manu', age: 29 },
{ id: 'asdf11', name: 'Stephanie', age: 26 }
],
otherState: 'some other value',
showPersons: false
}
nameChangedHandler = ( event, id ) => {//some other function}
togglePersonsHandler = () => {//some other function}
deletePersonHandler = (personIndex) => {
const persons = [...this.state.persons];
persons.splice(personIndex, 1);
this.setState({persons: persons});
}
render () {
const style = {
//some css styling
};
let persons = null;
if ( this.state.showPersons ) {
persons = (
<div>
{this.state.persons.map((person, index) => {
return <Person
click={() => this.deletePersonHandler(index)}
name={person.name}
age={person.age}
key={person.id}
changed={(event) => this.nameChangedHandler(event, person.id)} />
})}
</div>
);
}
return (
<div className="App">
<h1>Hi, I'm a React App</h1>
<p>This is really working!</p>
<button
style={style}
onClick={this.togglePersonsHandler}>Toggle Persons</button>
{persons}
</div>
);
}
}
Person Component
const person = ( props ) => {
return (
<div className="Person">
<p onClick={props.click}>I'm {props.name} and I am {props.age} years old!</p>
<p>{props.children}</p>
<input type="text" onChange={props.changed} value={props.name} />
</div>
)
};