when i change the date using input date filed the checkbox value has to change respect to the date but here every date is showing the same value for check box i have given the entire working code i have tryed in the codesandbox
<div>
<input type="date" onChange={this.dateHandler} />
</div>
{this.state.items.map((personData) => {
return (
<>
{" "}
<div className="activity">
<div className="inneractivity" style={styles.gridstyle}>
<div style={styles.txt}>
<h5>{personData.mainModule}</h5></div>
<div style={{ padding: "10px" }}>
<div
className="aflex-inner"
style={styles.gridstyleinner}
>
{personData.sub_module.map((subModule, key) => {
return (
<div key={subModule.id}>
<p style={styles.pstyle}>
{" "}
{subModule.subModuleName}
</p>
<input
type="checkbox"
data-id={subModule.id}
onChange={(e) =>
this.handleCheckClick(e, "items", key)
}
defaultChecked={
subModule.completed && subModule
}
/>
</div>
);
})}
</div>
</div>
</div>
</div>
</>
);
})}
entire working code
https://codesandbox.io/s/snowy-firefly-rs78v?file=/src/App.js
CodePudding user response:
Thank you for sharing such a complete reproduction!
I'm not sure how the logic should work here in detail--I assume that when clicking the checkbox, the post request saves data to the server, which then gets re-requested later. When it's re-requested, it should have the correct value in the completed
field for sub_modules
.
I can spot one issue relating to this behaviour:
prevState[index].completed = e.target.checked;
The prevState
is an array of personData
. Hence with prevState[index]
you are finding a personData
item. If I understood correctly, you want to find a sub_module
.
This could be done like so
prevState[<personDataIndex>].sub_module[<subModuleIndex>].completed
In your render function you are looping in this fashion
this.state.items.map((personData) => (
// ...
{personData.sub_modules.map((subModule, key) => (
// ...
<input onChange={(e) => this.handle(e, "items", key)} />
// ...
))}
))
Attempt to provide index values for both of the arrays you are looping
this.state.items.map((personData, i) => (
personData.sub_modules.map((subModule, j) => (
<input onChange={(e) => this.handleCheckClick(e, "items", i, j)} />
))
))
And then in the handleCheckClick handler set completed like so
prevState[i].sub_module[j].completed = e.target.checked
Also consider using checked
instead of defaultChecked
because the input is controlled
<input type="checkbox" checked={subModule.checked} />
Another issue with your example was that you were not passing the date
when you requested the data, but someone else or you yourself already fixed this issue.