React data table component, passing info for clicked row into modal - javascript

I'm making an offline PWA with ReactJS and I've started using the react-data-table-component, which has been great so far.
I've set the table to have an onRowClicked function that is called anytime a row is clicked, and so far, I only have that function opening a modal upon click which does indeed work.
My issue is that I want the modal to contain information from the row elements for the row that was clicked. So basically, if I click the first row that has the title "Hello There" (element.title) I want the modal to also contain the elements for that row.
This code shows everything I have, including how I'm mapping my documents from PouchDB into the elements object , which is what informs the rows in my data table.
What do I need to do in order to pass the info for the clicked row into the modal?
import React, { useState,useMemo} from 'react';
import { Column, Row } from 'simple-flexbox';
import { StyleSheet, css } from 'aphrodite/no-important';
const columns = [
{
name: 'Title',
sortable: true,
cell: row => (<div>{row.title}</div>),
},
{
name: 'Date of Entry',
selector: 'createdAt',
sortable: true,
right: true,
},
];
class MedJournalComponent extends React.Component {
constructor(props){
super(props);
this.state = {
loading: true,
elements: null,
notebookDisplayOpen: false
};
this.fetchData.bind(this);
}
componentDidMount(){
this.fetchData();
}
fetchData = () => {
this.setState({
loading: true,
elements: null,
});
this.props.notes.db.allDocs({
include_docs: true,
}).then(result => {
const rows = result.rows;
this.setState({
loading:false,
elements: rows.map(row => row.doc),
});
}).catch((err) =>{
console.log(err);
});
}
notebookEntryHandler = () => {
this.setState({notebookDisplayOpen: true});
}
closeNotebookEntry = () => {
this.setState({notebookDisplayOpen: false});
}
render() {
const { notebookDisplayOpen } = this.state;
if (this.state.loading || this.state.elements === null) {
return `loading...`;
}
return (
<Column>
<Modal open={notebookDisplayOpen} onClose={this.closeNotebookEntry}>
<div>Test</div>
</Modal>
<DataTable
title="Notebook Entries"
columns={columns}
data={this.state.elements}
theme="solarized"
selectableRows
onRowClicked={this.notebookEntryHandler}
Clicked
Selected={handleChange}
/>
</Column>
);
}
}
export default MedJournalComponent;

change:
notebookEntryHandler = () => {
this.setState({notebookDisplayOpen: true});
}
to:
notebookEntryHandler = row => {
this.setState({notebookDisplayOpen: true});
}
row represents the clicked row, you can store it in state and use it in the modal.

Related

Don't know how to handle input in my project

I'm working under the to-do list project and have got a problem with adding a comment to my list item. This is what I have right now:
App flow
After adding a list item you should be able to click in this item and a new window with comments will appear. In the comments section, comments should be added with Ctrl+Enter combination.
I've got a problem with adding comments to the list item (they should be added to the "comments" array of a particular list item).
Could you please explain what I'm doing wrong and why my comments aren't adding.
UPDATE: I've updated my code but the following mistake appears when I press Ctr+Enter to add a comment: [Error] (http://joxi.ru/Q2KR1G3U4lZJYm)
I've tried to bind the addItem method but no result. What's wrong with the addItem method?
Here is my main component:
App.js
import React, { Component } from 'react';
import './App.css';
import ListInput from './components/listInput'
import ListItem from './components/listItem'
import SideBar from './components/sideBar'
import CommentsSection from './components/commentsSection'
class App extends Component {
constructor(props){
super(props);
this.state = {
items: [
{
id: 0,
text: 'First item',
commentsCount: 0,
comments: [],
displayComment: false
},
{
id: 1,
text: 'Second item',
commentsCount: 0,
comments: [],
displayComment: false
},
{
id: 2,
text: 'Third item',
commentsCount: 0,
comments: [
'Very first comment',
'Second comment',
],
displayComment: false
},
],
nextId: 3,
activeComment: [],
}
}
// Add new item to the list
addItem = inputText => {
let itemsCopy = this.state.items.slice();
itemsCopy.push({id: this.state.nextId, text: inputText});
this.setState({
items: itemsCopy,
nextId: this.state.nextId + 1
})
}
// Remove the item from the list: check if the clicked button id is match
removeItem = id =>
this.setState({
items: this.state.items.filter((item, index) => item.id !== id)
})
setActiveComment = (id) => this.setState({ activeComment: this.state.items[id] });
addComment = (inputComment, activeCommentId ) => {
// find item with id passed and select its comments array
let commentCopy = this.state.items.find(item => item.id === activeCommentId)['comments']
commentCopy.push({comments: inputComment})
this.setState({
comments: commentCopy
})
}
render() {
return (
<div className='App'>
<SideBar />
<div className='flex-container'>
<div className='list-wrapper'>
<h1>Items</h1>
<ListInput inputText='' addItem={this.addItem}/>
<ul>
{
this.state.items.map((item) => {
return <ListItem item={item} key={item.id} id={item.id} removeItem={this.removeItem} setActiveComment={() => this.setActiveComment(item.id)}/>
})
}
</ul>
</div>
<CommentsSection inputComment='' items={this.state.activeComment}/>
</div>
</div>
);
}
}
export default App;
and my Comments Section component:
commentsSection.js
import React from 'react';
import './commentsSection.css';
import CommentInput from './commentInput'
import CommentsItem from './commentsItem'
export default class CommentsSection extends React.Component {
constructor(props){
super(props);
this.state = {value: this.props.inputComment};
this.handleChange = this.handleChange.bind(this);
this.handleEnter = this.handleEnter.bind(this);
this.addComment = this.addComment.bind(this)
}
handleChange = event => this.setState({value: event.target.value})
handleEnter(event) {
if (event.charCode === 13 && event.ctrlKey) {
this.addComment(this.state.value)
}
}
addComment(comment) {
// Ensure the todo text isn't empty
if (comment.length > 0) {
this.props.addComment(comment, this.props.activeComment);
this.setState({value: ''});
}
}
render() {
return (
<div className='component-section'>
<h1>{this.props.items.text}</h1>
<ul>
{ this.props.items.comments &&
this.props.items.comments.map((comment, index) => <p key={index}>{comment}</p>)
}
</ul>
<CommentsItem />
{/*<CommentInput />*/}
<div className='comment-input'>
<input type='text' value={this.state.value} onChange={this.handleChange} onKeyPress={this.handleEnter}/>
</div>
</div>
)
}
}
Change your CommentSection component addComment method and handleEnter method
addComment(comment) {
// Ensure the todo text isn't empty
if (comment.length > 0) {
// pass another argument to this.props.addComment
// looking at your code pass "this.props.items"
this.props.addComment(comment, this.props.items.id);
this.setState({value: ''});
}
}
handleEnter(event) {
if (event.charCode === 13 && event.ctrlKey) {
// passing component state value property as new comment
this.addComment(this.state.value)
}
}
Change your App Component addComment method
addComment = (inputComment, activeCommentId )=> {
// find item with id passed and select its comments array
let commentCopy = this.state.items.find(item => item.id === activeCommentId)['comments']
// if you want to push comments as object
// but looking at your code this is not you want
// commentCopy.push({comments: inputComment})
// if you want to push comments as string
commentCopy.push( inputComment)
this.setState({
comments: commentCopy
})
}

React 'this' undefined when adding table row

I'm attempting to add a new row of data to a table that occurs when a user inputs text into a field and clicks a button.
The button click is tied to a function (AddNewRow) which sends the data to a controller and then adds a new row to the table with the data.
The data is sent to the controller correctly and if the page is refreshed the new row is showing (because of the get request after mount) but the problem is the table doesn't update dynamically.
I keep getting a console error saying 'this is undefined' in the AddNewRow function.
Ive attempted to bind 'this' to the constructor by using both '.bind(this)' and AddNewRow() => {} but it still doesn't bind?
class App extends React.Component {
constructor() {
super();
this.state = {
tableData: [{
}],
};
}
componentDidMount() {
axios.get('/Jobs/GetJobs', {
responseType: 'json'
}).then(response => {
this.setState({ tableData: response });
});
}
AddNewRow(){
axios.post('/Controller/CreateJob', { Name: this.refs.NewJobName.value})
.then(function (response){
if(response.data.Error) {
window.alert(response);
}
else {
var data = this.setState.tableData;
this.setState.tableData.push(response);
this.setState({ tableData: data });
}
})}
render() {
const { tableData } = this.state;
return (
<div>
<button onClick={() => this.AddNewRow()} >ADD</button>
<input ref="NewJobName" type="text" placeholder="Name" />
<ReactTable
data={tableData}
/>
</div>
)
}
Use arrow function to make this available in the then function:
axios
.post('/Controller/CreateJob', { Name: this.refs.NewJobName.value })
.then((response) => {
if (response.data.Error) {
window.alert(response);
} else {
this.setState(prevState => ({
tableData: prevState.tableData.concat([response])
}));
}
});

updating React Table to not have any rows selected after submission

EDIT -
I am using this example here of the react-table select table (HOC)
Simply adding this code in the example code at the link mentioned above provides the results I am trying to achieve.
logSelection = () => {
console.log('selection:', this.state.selection);
this.setState({ selection: [] });
}
Background
I am using react-table in my React.js application. Specifically I am using the select table which provides a check box next to each row. In my case this allows the user to select multiple rows. Once the user submits their selections the data from the rows they selected is sent off for other use in my application.
After submission I am clearing the data that is being held in state. This is important in case they need to make another submission directly afterwords. After I clear the data from the state array holding each row that had previously been selected, the table still shows the previous rows selected even though the data is no longer being held in the state array.
Example Code
This is how I am clearing the array holding the selected arrays,
exportExcel() {
this.setState({ selection: [], selectAll: false });
}
This is all the relevant code in the class,
import React, {Component} from 'react';
import _ from 'lodash';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Form, FormGroup, Label, Input } from 'reactstrap';
import ReactTable from 'react-table';
import checkboxHOC from 'react-table/lib/hoc/selectTable';
import 'react-table/react-table.css';
import Chance from 'chance';
import { connect } from 'react-redux';
import { fetchOdx } from '../../store/actions/Odx';
const CheckboxTable = checkboxHOC(ReactTable);
const chance = new Chance();
class TypeAHead extends Component {
constructor(props) {
super(props);
this.state = {
showRow: false,
showExcelForm: false,
modal: false,
selection: [],
selectAll: false,
state: {},
row: {},
column: {},
instance: {},
data: [],
};
this.showRow = this.showRow.bind(this);
this.showExcelForm = this.showExcelForm.bind(this);
this.toggleSelection = this.toggleSelection.bind(this);
this.toggleAll = this.toggleAll.bind(this);
this.isSelected = this.isSelected.bind(this);
this.exportExcel = this.exportExcel.bind(this);
this.setClientEmail = this.setClientEmail.bind(this);
this.props.fetchOdx();
}
componentWillReceiveProps(nextProps) {
if (nextProps.odxData) {
this.setState({
data: nextProps.odxData
});
}
}
showRow() {
this.setState({
showRow: !this.state.showRow
});
}
showExcelForm() {
this.setState({
clientEmail: '',
showExcelForm: !this.state.showExcelForm
});
}
toggleSelection(key, shift, row) {
let selection = [
...this.state.selection
];
const keyIndex = selection.indexOf(key);
if (keyIndex >= 0) {
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
selection.push(row);
}
this.setState({ selection });
}
toggleAll() {
const selectAll = this.state.selectAll ? false : true;
const selection = [];
if (selectAll) {
const wrappedInstance = this.checkboxTable.getWrappedInstance();
const currentRecords = wrappedInstance.getResolvedState().sortedData;
currentRecords.forEach((item) => {
selection.push(item._original._id);
});
}
this.setState({ selectAll, selection });
}
isSelected(key) {
this.state.selection.includes(key);
}
setClientEmail(event) {
this.setState({ clientEmail: event.target.value.toLowerCase() });
}
exportExcel(event) {
this.setState({ selection: [], selectAll: false });
this.showExcelForm();
}
render() {
const { toggleSelection, toggleAll, isSelected } = this;
const { selectAll, } = this.state;
const checkboxProps = {
toggleSelection,
toggleAll,
isSelected,
selectAll,
selectType: 'checkbox',
};
const columns = [{
Header: 'DebtCltRefNo',
accessor: 'DebtCltRefNo'
}, {
Header: 'DbtrDebtorType',
accessor: 'DbtrDebtorType',
}];
return (
<div>
<Button onClick={this.showExcelForm} color="success" size="lg" block>Export Excel</Button>
<CheckboxTable
data={this.state.data}
columns={columns}
className="-striped -highlight"
defaultPageSize={10}
ref={(r) => this.checkboxTable = r}
filterable
defaultFilterMethod={(filter, row) =>
String(row[filter.id]) === filter.value}
getTdProps={(state, row, column, instance) => ({
onClick: e => {
const r = row.original;
this.setState({ state, row: r, column, instance });
this.showRow();
}})}
{...checkboxProps}
/>
<div>
<Modal isOpen={this.state.showRow} toggle={this.showRow}>
<ModalHeader toggle={this.showRow}>{this.state.row.DebtCltRefNo}</ModalHeader>
<ModalBody>
DbtrDebtorType: {this.state.row.DbtrDebtorType}<br />
DebtType: {this.state.row.DebtType}<br />
</ModalBody>
<ModalFooter>
<Button color="danger" onClick={this.toggle}>Cancel</Button>
</ModalFooter>
</Modal>
</div>
<div>
<Modal isOpen={this.state.showExcelForm} toggle={this.showExcelForm}>
<ModalHeader toggle={this.showExcelForm}>Grant Client Access</ModalHeader>
<ModalBody>
<Form>
<FormGroup>
<Label for="clientEmail">Client's Email Address</Label>
<Input value={this.state.clientEmail} onChange={this.setClientEmail} type="email" name="clientEmail" id="clientEmail" placeholder="Client's Email Address" />
</FormGroup>
</Form>
</ModalBody>
<ModalFooter>
<Button color="danger" onClick={this.showExcelForm}>Cancel</Button>
<Button color="success" onClick={this.exportExcel}>Submit</Button>
</ModalFooter>
</Modal>
</div>
</div>
);
}
}
const mapStateToProps = state => {
if (state.Odx.odx) {
let data = state.Odx.odx;
data = _.forEach([...data], (o) => o._id = chance.guid());
return {
odxData: data
};
} else {
return {};
}
};
const mapDispatchToProps = dispatch => ({
fetchOdx: () => dispatch(fetchOdx()),
});
export default connect(mapStateToProps, mapDispatchToProps)(TypeAHead);
Question
How do I make the table update after my form is submitted, so that no rows have a check box checked? Or in other words, how can I get the table to coincide with the state array which shows the rows that have been selected? In my case, after I update the state array to be an empty array, the selected rows are still selected in the UI.
Try useTable({columns, data, defaultColumn, autoResetPage: !skipPageReset, updateMyData, autoResetSelectedRows: false}, ...)
Adding the autoResetSelectedRows: false option worked for me.

React.js moving on to the next list

I'm making a movie search page. When I search something, it goes through the data base and find the very first match and display on the page. However, I want to create a function, so when I click next, page displays next movie in the data base. My code follows:
import React, { Component, PropTypes } from 'react';
import SearchBar from './Bar/index.js';
import SearchResult from './Result/index.js';
import axios from 'axios';
import './index.css';
class SearchArea extends Component {
constructor(props) {
super(props);
this.state = {
searchText: '',
searchResult: {},
result: false,
count: 0
};
}
handleSearchBarChange(event) {
this.setState({searchText: event.target.value});
}
handleSearchBarSubmit(event) {
event.preventDefault();
const movie = this.state.searchText;
axios.get(`https://api.themoviedb.org/3/search/movie?api_key=c6cd73ec4677bc1d7b6560505cf4f453&language=en-US&query=${movie}&page=1&include_adult=false`)
.then(response => {
if(response.data.results.length >= 0) {
const i = 0;
const {
title,
overview,
release_date: releaseDate
} = response.data.results[this.state.count];
const posterPath = 'https://image.tmdb.org/t/p/w154' + response.data.results[this.state.count].poster_path;
this.setState({
searchResult: {
title,
posterPath,
overview,
releaseDate
},
result: true
});
}
else {
this.setState({
searchResult: {
title: 'No Result',
overview: 'No Overview Available',
posterPath: ''
},
result: true
});
}
})
}
handleSearchNext(event) {
this.handelSearchBarSubmit.overview = response.data.results[1];
}
handleResultClose() {
this.setState({
searchResult: {},
result: false
});
}
render() {
return (
<div>
<SearchBar
value = {this.state.searchText}
onChange = {this.handleSearchBarChange.bind(this)}
onSubmit = {this.handleSearchBarSubmit.bind(this)}
onNext = {this.handleSearchNext.bind(this)}
/>
{this.state.result &&
<SearchResult
searchResult = {this.state.searchResult}
onClose = {this.handleResultClose.bind(this)}
onAdd = {this.props.onAdd}
/>
}
</div>
);
}
}
SearchArea.propTypes = {
onAdd: PropTypes.func.isRequired
};
export default SearchArea;
I can't seem to figure out how to make handleSearchNext. Please help
EDIT
Following is the SearchBar code
import React, { PropTypes } from 'react';
import { Button } from 'semantic-ui-react';
import styles from './index.css';
const SearchBar = (props) => {
return (
<div>
<form onSubmit={(event) => props.onSubmit(event)}>
<input
className="searchBar"
type="text"
placeholder="Search Here"
value={props.value}this
onChange={(event) => props.onChange(event)}
onNext={(event) => props.onChange(event)}
onBack={(event) => props.onChange(event)}
/>
<Button className="button" type="submit">Sumbit</Button>
</form>
<Button className={styles.button} type="previous">Back</Button>
<Button className="button" type="next">Next</Button>
</div>
);
};
SearchBar.propTypes = {
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onBack: PropTypes.func.isRequired,
onNext: PropTypes.func.isRequired
};
export default SearchBar;
You could have your server respond with not only the requested title, but also the next one. That way, when you click on Next, you can immediately display the next movie without waiting for a response, while still querying it in the background by name or id (so that you have the next after it, etc.).
Edit: If I misunderstood what you meant and you already have this (it looks like you are actually querying a whole page of movies at once), you probably simply want something like
handleSearchNext(event) {
this.setState({ searchResult: response.data.results[1], result: true });
}
and handle specially the case when you hit the last item on the page.

React Modal Does Not Close In Between Loading Content

I'm using this react modal plugin: https://github.com/reactjs/react-modal
and I need to show an array of objects in the modal on page load. When the first item shows user clicks a button so isOpen prop is set to false for Modal. Each item has a prop showModal that feeds the value to isOpen for the Modal. As the user keeps clicking I keep setting the value on the current object to false and then set it true for the next object.
This is all working fine but the problem is that the overlay and dialog window stays on screen and only content within the modal is updated. I would like the modal to fully close and open to show content of the next object in array. I had to strip out my code to a simplified version below:
class ProductsModal extends React.Component {
constructor(props) {
super(props);
this.remindMeHandler = this.remindMeHandler.bind(this);
this.state = {
products: [],
modalId: 0
};
}
showModals() {
let products = this.state.products;
//A different function saves the array of product objects in the state so
//I can show them one by one
let currentProduct = products[this.state.popUpId];
if (products.length > 0) {
return <ProductItemModal
product={currentProduct}
showNextPopUp={() => this.showNextPopUp(currentProduct.productId)}
showPopUp={currentProduct['showModal']}
/>;
//showModal is a boolean for each product that sets the value of isOpen
}
}
showNextPopUp() {
//All this does is sets the "showModal" property to false for current
//product and sets it to true for next product so it shows in the Modal
}
render() {
return(
<div>
{this.showModals()}
</div>
);
}
}
class ProductItemModal extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<Modal
isOpen={this.props.showModal}
contentLabel="Product"
id={this.props.product.productId}
>
<div>
Product Data......
</div>
</Modal>
);
}
}
Had a workaround for all your problems and created this codepen link. It would be like this,
class ProductItemModal extends React.Component {
render() {
const { showModal, product, showNextModal, onClose } = this.props;
return(
<ReactModal
isOpen={showModal}
contentLabel="Product"
onRequestClose={() => onClose()}
>
<p>
<b>Product Id</b> - {product.id}, <b>Product Name</b> - {product.name}
</p>
<button onClick={() => showNextModal()}>Next</button>
</ReactModal>
);
}
}
class ProductsModal extends React.Component {
constructor() {
super();
this.state = {
products: [
{id: 1, name: "Mac", showModal: true},
{id: 2, name: "iPhone", showModal: false},
{id: 3, name: "iPod", showModal: false},
],
modalId: 0
};
}
handleProductItemModalClose(product) {
//backdrop click or escape click handling here
console.log(`Modal closing from Product - ${product.name}`);
}
showModals() {
const { products, modalId } = this.state;
//A different function saves the array of product objects in the state so
//I can show them one by one
let currentProduct = products[modalId];
if(currentProduct) {
return <ProductItemModal
product={currentProduct}
showNextModal={() => this.showNextModal(currentProduct.id)}
showModal={currentProduct["showModal"]}
onClose={() => this.handleProductItemModalClose(currentProduct)}
/>;
//showModal is a boolean for each product that sets the value of isOpen
}
}
showNextModal(currentProductId) {
const { products, modalId } = this.state;
var isLastModal = false;
if(modalId === products.length - 1) {
isLastModal = true;
}
var clonedProducts = [...products];
var currentIndex = clonedProducts.findIndex(product => product.id === currentProductId);
var newIndex = currentIndex + 1;
clonedProducts[currentIndex].showModal = false;
if(!isLastModal) {
clonedProducts[newIndex].showModal = true;
} else {
//comment the following lines if you don't wanna show modal again from the start
newIndex = 0;
clonedProducts[0].showModal = true;
}
//All this does is sets the "showModal" property to false for current
//product and sets it to true for next product so it shows in the Modal
this.setState({
products: clonedProducts
}, () => {
this.setState({
modalId: newIndex
});
});
}
render() {
return(
<div>
{this.showModals()}
</div>
);
}
}
ReactDOM.render(<ProductsModal />, document.getElementById("main"));
Let me know if it helps.
Updated codepen: https://codepen.io/anon/pen/rzVQrw?editors=0110
You need to call setState() of ProductItemModal to close Model. Otherwise, though isOpen is changed, the UI is not re-rendered.
As you probably know that react maintain a virtual DOM and on every time state or props change it compares the difference between browser's DOM(actual dom) and virtual DOM(the one that React maintain) and in your code every time you change the isOpen property all you are doing is only changing the props of the Model component that's why React only update the internal content of the actual Model
to completely close and re-open the model you need to do a small change in your code
instead of returning only one model component in your ProductsModal you need to do something like this so that react know that this modal has been close and otherone has been open Key property is important for performance reason read more
class ProductsModal extends React.Component {
.
.
.
showModals() {
let products = this.state.products;
//A different function saves the array of product objects in the state so
if (products.length > 0) {
return (
//return list of all modal component
products.map((product) =>
<ProductItemModal
product={product}
showNextPopUp={() => this.showNextPopUp(product.productId)}
showPopUp={product['showModal']}
key={product.productId}
/>
)
);
//showModal is a boolean for each product that sets the value of isOpen
}
}
.
.
.
}
all you are doing here is just returning multiple modal and when one model gets the isOpen props as false is close and the other witch gets true is open and now react know that there are two different modals because of key props
Another work around is to use setTimeout. Implementation is as follows-
class ProductItemModal extends React.Component {
render() {
const { showModal, product, selectNextProductFunc, onClose } = this.props;
return(
<ReactModal
isOpen={showModal}
contentLabel="Product"
onRequestClose={() => onClose()}
>
<p>
<b>Product Id</b> - {product.id}, <b>Product Name</b> - {product.name}
</p>
<button onClick={() => selectNextProductFunc(product)}>Next</button>
</ReactModal>
);
}
}
class ProductsModal extends React.Component {
constructor() {
super();
this.state = {
products: [
{id: 1, name: "Mac"},
{id: 2, name: "iPhone"},
{id: 3, name: "iPod"},
],
productId: null,
showModal: true,
};
}
handleProductItemModalClose(product) {
//backdrop click or escape click handling here
console.log(`Modal closing from Product - ${product.name}`);
}
showModals() {
const { products, productId, showModal} = this.state;
//A different function saves the array of product objects in the state so
//I can show them one by one
const getProduct = function(){
if(productId){
return products.find((i) => i.id === productId);
}else{
return products[0]; // first element
}
}
return <ProductItemModal
product={getProduct()}
selectNextProductFunc={this.selectNextProductFunc.bind(this)}
showModal={showModal}
onClose={() => this.handleProductItemModalClose()}
/>;
//showModal is a boolean for each product that sets the value of isOpen
}
selectNextProductFunc(currentProduct) {
const { products} = this.state;
this.setState({
showModal: false
});
const currentProductIndex = products.findIndex((i) => i.id === currentProduct.id);
const modifiedIndex = 0;
if(products[currentProductIndex + 1]){
this.setState({
productId : products[currentProductIndex + 1].id,
});
}else{
this.setState({
productId : modifiedIndex,
});
}
setTimeout(() => {
this.setState({
showModal: true
})
}, 1000);
}
render() {
return(
<div>
{this.showModals()}
</div>
);
}
}
ReactDOM.render(<ProductsModal />, document.getElementById("main"));
jsbin

Categories

Resources