My Objective is to show error to the particular object id when we dont enter any value in the textfield in onChange method. But it is appearing in the other id text field.
JSON data looks in this way:
"details": [
{ "id": "12wer1", "name": "ABC", "age": 15 },
{ "id": "78hbg5", "name": "FRE", "age": 21 }
]
I've tried in this way:
{this.state.details.map((y) => (
<Grid container justify="center" spacing={2}>
<Grid item xs={3}>
<TextField label="Name" name="dName" variant="outlined" value={y.name}
onChange={(e)=>this.onChange(e.target.name, e.target.value)}
/>
</Grid>
<Grid item xs={3}>
<TextField label="Age" name="age"variant="outlined" value={y.age} onChange={(e)=>this.onChange(e.target.name, e.target.value)}/>
<FormHelperText >
{this.state.errors.age}
</FormHelperText>
</Grid>
</Grid>
))}
OnChange method:
onChange = (name, value)=> {
this.state.details.forEach((item) => {
if (!item.age) {
errors.age = "age is required";
}
else {
errors.age = ""
}
}
I'm getting error in other ids also. for example i want to clear the age for 1st id then error is showing on both the ids.
Can anyone help me to fix this error?