Reputation: 10240
I have a table that displays a number of records from a json (dynamically). When you click on the desired row, you get a dialog with actions within it (records count, reject, approve, close dialog, next record, and previous record).
I have pretty much all of it working except the next and prev functionality. I thought a ++
and --
on the rowIndex
would fetch the next iteration (this is my angularJS thought process by the way, since I created this already in Angular but we are converting to ReactJS), but obviously, it doesn't work that way.
These are the functions I created, however, you can see a minimalist code snippet in my webpackbin that you can use to play around with it:
//Pull the next item
handleApprovalDialogNext = (rowIndex, openIndex, event) => {
this.setState(
{
openIndex: rowIndex++,
}, () => {this.setState({ open: true })}
)
};
//Pull the prev item
handleApprovalDialogPrev = (rowIndex, openIndex, event) => {
this.setState(
{
openIndex: rowIndex--,
}, () => {this.setState({ open: true })}
)
};
Here is a link to my webpackbin
p.s. Ideally, if the item is the first one, it shouldn't allow you to go back (perhaps, disabling the arrow icon). Same thing when you reach the end of the data.
Any help would be really appreciated.
Upvotes: 0
Views: 417
Reputation: 16441
You're webpackbin is getting errors and won't load. However, I think you should be adding/subtracting from this.state.openIndex
rather than rowIndex
. Not sure why you are setting open in the callback. Setstate callback is discouraged in the React docs https://facebook.github.io/react/docs/react-component.html#setstate.
//Pull the next item
handleApprovalDialogNext = (rowIndex, openIndex, event) => {
this.setState({
openIndex: this.state.openIndex + 1,
open: true
});
};
//Pull the prev item
handleApprovalDialogPrev = (rowIndex, openIndex, event) => {
this.setState({
openIndex: this.state.openIndex - 1,
open: true
});
};
Also, check out How to uses increment operator in React to know why you should use + 1
rather than ++
.
To render the icons conditionally, you just need to check if the current openIndex is the first or last index in the data.
It would look something like this:
<Col className="floating-close layout-column">
<IconButton>
<i className="material-icons">close</i>
</IconButton>
{this.state.openIndex > 0 &&
<IconButton>
<i className="material-icons left">chevron_left</i>
</IconButton>}
{this.state.openIndex < approvalsData.length &&
<IconButton>
<i className="material-icons right">chevron_right</i>
</IconButton>}
</Col>
Upvotes: 2