When I am trying to access removeperson
or renamefun
within the class its working but when I am trying to access them from some other function component it is giving error Cannot read property 'persons' of undefined
1. Below is the code of my class component
import './App.css';
import { Component } from 'react';
import Allpersons from '../Components/Allpersons/Allpersons';
import Person from '../Components/Person/Person';
class App extends Component {
state ={
persons : [
{id:'ha1f' ,name :'harsh' , age : 25} ,
{id: 'jak2' ,name :'mohit', age: 23} ,
{id:'adsf23',name :'sachin' , age: 29}
],
c:0 ,
personview: false
}
togglepersonview=()=>{
const val=this.state.personview;
this.setState({personview:!val});
}
removeperson(index)
{
const people=[...this.state.persons];
people.splice(index,1);
this.setState({persons:people})
}
renamefun(event,id){
const personindex=this.state.persons.findIndex(p => {
return p.id===id; //will store values of only person which has id equal to id;
});
const personvalues={
...this.state.persons[personindex]
};
personvalues.name=event.target.value;
const people=[...this.state.persons];
people[personindex]=personvalues;
this.setState({persons :people});
}
render(){
const style={
padding :'4px 6px' ,
color:'white',
backgroundColor:'green',
border:'1px solid grey'
}
var showperson=null;
if(this.state.personview){
showperson=(
<div>
<Allpersons
persons={this.state.persons}
clickrename={this.renamefun}
clickremove={this.removeperson}
/>
</div>
);
style.backgroundColor='red';
}
let styleclass=[];
if(this.state.persons.length<=2){
styleclass.push("bold");
}
if(this.state.persons.length<=1){
styleclass.push("red");
}
styleclass=styleclass.join(" ");
return (
<div className="App">
<h1>react</h1>
<p>{this.state.c}</p>
<p className={styleclass}>Here I am using the styleclass.</p>
<button style={style} onClick={this.togglepersonview}>switch view</button>
{showperson}
</div>
);
}
}
export default App;
2. BELOW IS THE CODE OF MY FUNCTION COMPONENT
import React from 'react';
import Person from '../Person/Person';
const Allpersons=(props)=>props.persons.map((person,index)=>{
return (
<div>
<Person name= {person.name}
age = {person.age }
clickperson={()=>props.clickremove(index)}
key={person.id}
rename={(event)=>props.clickrename(event,person.id)}
/>
</div>
) })
export default Allpersons;