I have a problem where I am generating datepickers on the fly
based on a number of props passed down. The props passed down from the parent component are charges of a particular product. So say there a 6 charges, then we create an input field containing the charge and then for each one a corresponding datepicker needs to be displayed.
The image below hopefully displays this better than i could explain it! (Picture paints a thousand words they say!!)
So my problem is this, if the user updates all of the dates in the datepickers (to the right) then how do I save each date to the particular id? I would obviously store them in state, but how do i save each one?
I cant just have values in state pre-set as the number of datepickers and charges can be different each time. Sometimes there may be 1, sometimes there may be 10.
The code I have for this component is as follows:
export class Charges extends Component {
constructor(props) {
super(props);
this.state = {
currentItem: 0,
newDate: ''
fields: []
}
this.handleChange = this.handleChange.bind(this);
}
****** EDIT *********
handleDateChange = (e) => {
const date = e.target.value;
const chargeId = e.target.name;
console.log(date);
this.setState({
fields: [
...this.state.fields,
[chargeId]: date
]
}, () => console.log(this.state.fields))
}
**********
render() {
const {charges, chargeTypes} = this.props;
if (charges.length === 0) { return null; }
return <Form>
<h3>Charges</h3>
{charges.map(charge => {
console.log(charge);
const chargeType = chargeTypes.find(type => type.code === charge.type) || {};
return <Grid>
<Grid.Row columns={2}>
<Grid.Column>
<Form.Input
key={charge.id}
label={chargeType.description || charge.type}
value={Number(charge.amount).toFixed(2)}
readOnly
width={6} />
</Grid.Column>
<Grid.Column>
<DateInput
name={charge.id}
selected={this.state.newDate}
onChange={this.handleChange}
value={charge.effectiveDate}
/>
</Grid.Column>
</Grid.Row>
</Grid>
})}
<Divider hidden />
<br />
</Form>
}
}
As you can see, I will just overwrite previous' state value if the user was to update more than one datepicker?
I have viewed the following article, but its not really what i want: Multiple DatePickers React
How can i achieve the functionality I want? I hope I have made this clear? If there are any questions please don't hesitate to ask!
* Edited Answer *
I have now updated the handleDateChangeMethod to store the data in an array (as this is what I want) however, it only gives me the chargeId
and not the date mapped to it!
See screenshot below:
Is there anyway to save like this in the state array [chargeId: date]