React Native Redux Shopping Cart App Problems - reactjs

I am trying to make an application that allows the user to select 'Add to cart' within my DetailsComponent.js page. I am currently updating an array within my store named 'cart' with ids that correspond to products within a products array within the store. I have checked the debugger and the product id is correctly being added to the cart array.
I am using the following code to show products on my cart page that match the product ids in my cart but my cart is currently showing nothing.
CartComponent.js
import React, { Component } from 'react';
import { FlatList, View, Text, Alert } from 'react-native';
import { ListItem } from 'react-native-elements';
import { connect } from 'react-redux';
import { baseUrl } from '../shared/baseUrl';
import { Loading } from './LoadingComponent';
import { removeCart } from '../redux/ActionCreators';
const mapStateToProps = state => {
return {
products: state.products,
cart: state.cart
}
}
const mapDispatchToProps = dispatch => ({
removeCart: (id) => dispatch(removeCart(id))
});
class CartScreen extends Component {
render() {
const renderMenuItem = ({item, index}) => {
return(
<ListItem
key={index}
bottomDivider
>
<ListItem.Content>
<ListItem.Title>
{item.name}
</ListItem.Title>
<ListItem.Subtitle>
{item.quantity} chargers: ${item.price}
</ListItem.Subtitle>
</ListItem.Content>
</ListItem>
);
}
if (this.props.cart.isLoading) {
return(
<Loading />
)
}
else if (this.props.cart.errMess) {
return(
<Text>{this.props.cart.errMess}</Text>
)
}
else {
return(
<View>
<Text>
Cart
</Text>
<FlatList
data={this.props.products.products.filter(product => this.props.cart.cart.some(el => el === product.id))}
renderItem={renderMenuItem}
keyExtractor={item => item.id.toString()}
/>
</View>
);
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CartScreen);
I have included my other files for more information.
I have different DropDownPicker values that correspond to the product IDs in my redux store. These items in the store have quantity and price values to be used in the CartComponent.js.
DetailsComponent.js
import React, { Component } from 'react';
import { Text, View, Image, Button, FlatList, StyleSheet, ScrollView} from 'react-native';
import DropDownPicker from 'react-native-dropdown-picker';
import { baseUrl } from '../shared/baseUrl';
import { connect } from 'react-redux';
import { Loading } from './LoadingComponent';
import { postCart } from '../redux/ActionCreators';
const mapStateToProps = state => {
return{
chargers: state.chargers,
utensils: state.utensils,
orders: state.orders,
products: state.products
}
}
const mapDispatchToProps = dispatch => ({
postCart: (id) => dispatch(postCart(id))
})
class DetailsScreen extends Component {
constructor(props) {
super();
this.state = {
itemId: '',
orderAmount: '',
orderPrice: ''
}
}
addToCart(id) {
this.props.postCart(id);
}
render() {
const categoryName = this.props.route.params.categoryName;
const productId = this.props.route.params.menuId;
const item = this.props[categoryName][categoryName][productId];
if (categoryName === "chargers") {
if (productId === 0) {
var amounts = [
{label: '50', value: '1'},
{label: '100', value: '2'},
{label: '150', value: '3'},
{label: '200', value: '4'},
{label: '250', value: '5'},
{label: '300', value: '6'},
{label: '350', value: '7'},
{label: '400', value: '8'},
{label: '450', value: '9'},
{label: '500', value: '10'},
{label: '550', value: '11'},
{label: '600', value: '12'},
];
}
else if (productId === 1) {
var amounts = [
{label: '50', value: '14'},
{label: '100', value: '15'},
{label: '150', value: '16'},
{label: '200', value: '17'},
{label: '250', value: '18'},
{label: '300', value: '19'},
{label: '350', value: '20'},
{label: '400', value: '21'},
{label: '450', value: '22'},
{label: '500', value: '23'},
{label: '550', value: '24'},
{label: '600', value: '25'},
];
}
else if (productId === 2) {
var amounts = [
{label: '50', value: '27'},
{label: '100', value: '28'},
{label: '150', value: '29'},
{label: '200', value: '30'},
{label: '250', value: '31'},
{label: '300', value: '32'},
{label: '350', value: '33'},
{label: '400', value: '34'},
{label: '450', value: '35'},
{label: '500', value: '36'},
{label: '550', value: '37'},
{label: '600', value: '38'},
];
}
}
else if (categoryName === "utensils") {
if (productId === 0) {
var amounts = [
{label: '1', value: '40'},
{label: '2', value: '41'},
{label: '3', value: '42'},
{label: '4', value: '43'},
{label: '5', value: '44'},
];
}
else if (productId === 1) {
var amounts = [
{label: '1', value: '46'},
{label: '2', value: '47'},
{label: '3', value: '48'},
{label: '4', value: '49'},
{label: '5', value: '50'},
];
}
}
if (this.props[categoryName].isLoading) {
return(
<Loading />
)
}
else if (this.props[categoryName].errMess) {
return(
<Text>
{this.props[categoryName][categoryName].errMess}
</Text>
)
}
else {
return(
<ScrollView>
<Text style={styles.title}>
{item.name}
</Text>
<Text>
{item.category}
</Text>
<View style={{flex: 1, flexDirection: 'row'}}>
<Image
style={styles.image}
source={{uri: baseUrl + item.image}}
/>
<DropDownPicker
items={amounts}
defaultNull
placeholder="Select amount"
containerStyle={{height: 40, width: 100}}
itemStyle={{
justifyContent: 'flex-start'
}}
onChangeItem={item => this.setState({
itemId: this.props.products.products[item.value].id,
orderAmount: this.props.products.products[item.value].quantity,
orderPrice: this.props.products.products[item.value].price
})}
/>
</View>
<Text>
{item.description}
</Text>
<Text>
Your order is {this.state.orderAmount} {this.props[categoryName][categoryName][productId].name} chargers for ${this.state.orderPrice}
</Text>
<Button
title='Add to Cart'
color="#f194ff"
onPress={() => this.addToCart(this.state.itemId)}
/>
</ScrollView>
)
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
resizeMode: "contain",
height: 200,
width: 200
},
title: {
fontSize: 32,
},
});
export default connect(mapStateToProps, mapDispatchToProps)(DetailsScreen);
The following code samples are my redux files. I have simplified them with only the cart information for readability.
ActionCreators.js
export const fetchCart = () => (dispatch) => {
dispatch(cartLoading());
return fetch(baseUrl + 'cart')
.then(response => {
if (response.ok) {
return response;
} else {
var error = new Error('Error ' + response.status + ': ' + response.statusText);
error.response = response;
throw error;
}
},
error => {
var errmess = new Error(error.message);
throw errmess;
})
.then(response => response.json())
.then(cart => dispatch(addCart(cart)))
.catch(error => dispatch(cartFailed(error.message)));
};
export const cartLoading = () => ({
type: ActionTypes.CART_LOADING
});
export const cartFailed = (errmess) => ({
type: ActionTypes.CART_FAILED,
payload: errmess
});
export const postCart = (id) => (dispatch) => {
const newCart = {
id: id
};
setTimeout(() => {
dispatch(addToCart(newCart));
}, 2000);
};
export const addToCart = (cart) => ({
type: ActionTypes.ADD_TO_CART,
payload: cart
});
export const addCart = (id) => ({
type: ActionTypes.ADD_CART,
payload: id
});
export const removeCart = (id) => ({
type: ActionTypes.REMOVE_CART,
payload: id
});
ActionTypes.js
export const POST_CART = 'POST_CART';
export const ADD_TO_CART = 'ADD_TO_CART';
export const ADD_CART = 'ADD_CART';
export const REMOVE_CART = 'REMOVE_CART';
export const CART_LOADING = 'CART_LOADING';
export const CART_FAILED = 'CART_FAILED';
cart.js
import * as ActionTypes from './ActionTypes';
export const cart = (
state = {
isLoading: true,
errMess: null,
cart:[]
},
action) => {
switch (action.type) {
case ActionTypes.ADD_CART:
return {...state, isLoading: false, errMess: null, cart: action.payload};
case ActionTypes.CART_LOADING:
return {...state, isLoading: true, errMess: null, cart: []};
case ActionTypes.CART_FAILED:
return {...state, isLoading: false, errMess: action.payload};
case ActionTypes.ADD_TO_CART:
var newCart = action.payload;
return {...state, cart: state.cart.concat(newCart) };
default:
return state;
}
};
The following is my db.json file. I have input one item into the cart array for testing but it also does not show up in the cart. Have also simplified this file to only show a few products for readability.
"products": [
{
"id": 0,
"name": "Ezywhip Pro",
"category": "chargers",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 0,
"price": 0
},
{
"id": 1,
"name": "Ezywhip Pro",
"category": "ezy",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 50,
"price": 40
},
{
"id": 2,
"name": "Ezywhip Pro",
"category": "ezy",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 100,
"price": 70
},
{
"id": 3,
"name": "Ezywhip Pro",
"category": "ezy",
"label": "",
"featured": false,
"description": "Ezywhip Pro Cream Chargers, Made by MOSA",
"image": "images/ezywhip.png",
"quantity": 150,
"price": 110
}
],
"cart": [
{
"id": 1
}
]
}
If anyone could explain what I'm doing wrong it would be greatly appreciated.

I got it working by changing the following:
export const addToCart = (id) => ({
type: ActionTypes.ADD_TO_CART,
payload: id
});
Not sure if this was causing any issues but I changed it to id for safe measure.
This is what was causing the main issue, I needed to use el.id to specify that's what I was comparing with in the data.
<FlatList
data={this.props.products.products.filter(product => this.props.carts.carts.some(el => el.id === product.id))}
renderItem={renderMenuItem}
keyExtractor={item => item.id.toString()}
/>

Related

How can i use react-drag-listview with functional components to make draggable columns with antd-table?

I'm trying to create a draggable table with antd, but i always use functionalcomponents in react and all the examples and doc that i found in internet is using class components and that=this stufs like. I don't know how can i use react-drag-listview library with the functional components.
this.state = {
columns: [
{
title: <span className="dragHandler">Key</span>,
dataIndex: "key",
render: (text) => <span>{text}</span>,
width: 50
},
{
title: <span className="dragHandler">Name</span>,
dataIndex: "name",
width: 200
},
{
title: <span className="dragHandler">Gender</span>,
dataIndex: "gender",
width: 100
},
{
title: <span className="dragHandler">Age</span>,
dataIndex: "age",
width: 100
},
{
title: <span className="dragHandler">Address</span>,
dataIndex: "address"
}
]
};
const that = this;
this.dragProps = {
onDragEnd(fromIndex, toIndex) {
const columns = [...that.state.columns];
const item = columns.splice(fromIndex, 1)[0];
columns.splice(toIndex, 0, item);
that.setState({
columns
});
},
nodeSelector: "th",
handleSelector: ".dragHandler",
ignoreSelector: "react-resizable-handle"
};
}
This a small piece of code that I'm trying to copy from, but i don't understand it.
Even an exaple of any small code where i can see how to use with functional components it may work for me.
Tis is the url of the example above: https://codesandbox.io/s/table-column-sortable-resizable-st9bt?file=/index.js
React Drag List View Using Functional Component
import "./index.css";
import { useState } from "react";
import { Resizable } from "react-resizable";
import { Table } from "antd";
import ReactDragListView from "react-drag-listview";
const ResizableTitle = (props) => {
const { onResize, width, ...restProps } = props;
if (!width) {
return <th {...restProps} />;
}
return (
<Resizable
width={width}
height={0}
handle={
<span
className='react-resizable-handle'
onClick={(e) => {
e.stopPropagation();
}}
/>
}
onResize={onResize}
draggableOpts={{ enableUserSelectHack: false }}
>
<th {...restProps} />
</Resizable>
);
};
const data = [
{ key: "1", name: "Boran", gender: "male", age: "12", address: "New York" },
{ key: "2", name: "JayChou", gender: "male", age: "38", address: "TaiWan" },
{ key: "3", name: "Lee", gender: "female", age: "22", address: "BeiJing" },
{ key: "4", name: "ChouTan", gender: "male", age: "31", address: "HangZhou" },
{ key: "5", name: "AiTing", gender: "female", age: "22", address: "Xi’An" },
];
const components = { header: { cell: ResizableTitle } };
const App = () => {
const [columns, setColumns] = useState([
{
title: <span className='dragHandler'>Key</span>,
dataIndex: "key",
render: (text) => <span>{text}</span>,
width: 50,
},
{
title: <span className='dragHandler'>Name</span>,
dataIndex: "name",
width: 200,
},
{
title: <span className='dragHandler'>Gender</span>,
dataIndex: "gender",
width: 100,
},
{
title: <span className='dragHandler'>Age</span>,
dataIndex: "age",
width: 100,
},
{
title: <span className='dragHandler'>Address</span>,
dataIndex: "address",
},
]);
const onDragEnd = (fromIndex, toIndex) => {
setColumns((prev) => {
const nextColumns = [...prev];
const item = nextColumns.splice(fromIndex, 1)[0];
nextColumns.splice(toIndex, 0, item);
return nextColumns;
});
};
const handleResize = (size, index) => {
setColumns((prev) => {
const nextColumns = [...prev];
nextColumns[index] = {
...nextColumns[index],
width: size.width,
};
return nextColumns;
});
};
const tableColumns = columns.map((col, index) => ({
...col,
onHeaderCell: (column) => ({
width: column.width,
onResize: (e, { size }) => handleResize(size, index),
}),
}));
return (
<ReactDragListView.DragColumn
onDragEnd={onDragEnd}
nodeSelector='th'
handleSelector='.dragHandler'
ignoreSelector='react-resizable-handle'
>
<Table bordered columns={tableColumns} dataSource={data} components={components} />
</ReactDragListView.DragColumn>
);
};
export default App;

Changing object in array using useState

I'd like to change each Data[0].datasets label using the array in Axisstate
I tried to put Axis's label to each Data label but i doesn't work, and it's not what i expected it would be.
both are changed to as same as the last one that i write.
and I'm trying to add more elements to datasets using the AxisHandler function to use push.
and It's doesn't change as soon as i click AxisUpdatefunction.
I'd like to know why it happens and what i should do .
Thank you in advance.
my code is like this:
import React, { useState } from "react";
import { Data, AppendData } from "./Data";
const Changeable = () => {
const [Axis, setAxis] = useState([]);
const changeHandler = index => e => {
setAxis(Axis =>
Axis.map((el, i) => (i === index ? { ...el, label: e.target.value } : el))
);
};
const AxisHandler = e => {
setAxis([
...Axis,
{
label: "",
data: "",
backgroundColor: "",
},
]);
Data[0].datasets.push(AppendData);
};
const AxisUpdate = () => {
if (Data[0].datasets[1].label) {
Data[0].datasets[1].label = Axis[0].label;
}
if (Data[0].datasets[2].label) {
Data[0].datasets[2].label = Axis[1].label;
}
};
return (
<div>
<button onClick={AxisHandler}>addAxis</button>
<>
{Axis.map((data, index) => (
<>
<input
placeholder={index + 1}
type="text"
onChange={changeHandler(index)}
/>
</>
))}
</>
<button onClick={AxisUpdate}>changeLabel</button>
<br />
<h1>{Data[0].datasets[0].label}</h1>
<br />
<h1>{Data[0].datasets[1] && Data[0].datasets[1].label}</h1>
<br />
<h1>{Data[0].datasets[2] && Data[0].datasets[2].label}</h1>
</div>
);
};
export default Changeable;
Data and AppendData
export const defaultLabels = [
"0",
"0",
"0",
"0",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
];
export const defaultDatas = [
13000, 11000, 9000, 4000, 14000, 16000, 20000, 11000, 14000, 11200, 12000,
12000,
];
export const defaultBackgroundColor = [
"#ff6385e1",
"#36a3ebf0",
"#ffcf56c8",
"#4bc0c0be",
"#9966ffa2",
"#ffa040b2",
];
export let AppendData = {
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
};
export let Data = [
{
labels: defaultLabels,
datasets: [
{
label: "First",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
}, ///1번
{
labels: defaultLabels,
datasets: [
{
label: "Second",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
},
{
labels: defaultLabels,
datasets: [
{
label: "Third",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
},
]; ///2번

How to implement AddAdiditions in React Sematic UI using Hooks?

I want to have a drop down in my application which allows the user to add an item to the dropdown. I am using React Sematic UI.
Sematic UI Dropdown ALlowAdditions
I am new to react hooks and I want to know how I can implement the onChange and onAddition function using hooks.
import React, { Component } from 'react'
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 'English', text: 'English', value: 'English' },
{ key: 'French', text: 'French', value: 'French' },
{ key: 'Spanish', text: 'Spanish', value: 'Spanish' },
{ key: 'German', text: 'German', value: 'German' },
{ key: 'Chinese', text: 'Chinese', value: 'Chinese' },
]
class DropdownExampleAllowAdditions extends Component {
state = { options }
handleAddition = (e, { value }) => {
this.setState((prevState) => ({
options: [{ text: value, value }, ...prevState.options],
}))
}
handleChange = (e, { value }) => this.setState({ currentValue: value })
render() {
const { currentValue } = this.state
return (
<Dropdown
options={this.state.options}
placeholder='Choose Language'
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={this.handleAddition}
onChange={this.handleChange}
/>
)
}
}
export default DropdownExampleAllowAdditions
Any help would be greatly appreciated. Thanks in advance :)
import React, { useState } from "react";
import { Dropdown } from "semantic-ui-react";
const options = [
{ key: "English", text: "English", value: "English" },
{ key: "French", text: "French", value: "French" },
{ key: "Spanish", text: "Spanish", value: "Spanish" },
{ key: "German", text: "German", value: "German" },
{ key: "Chinese", text: "Chinese", value: "Chinese" }
];
const DropDownWithHooks = () => {
const [dropDownOptions, setDropDownOptions] = useState(options);
const [currentValue, setCurrentValue] = useState("");
const handleAddition = (e, { value }) => {
setDropDownOptions((prevOptions) => [
{ text: value, value },
...prevOptions
]);
};
const handleChange = (e, { value }) => setCurrentValue(value);
return (
<Dropdown
options={dropDownOptions}
placeholder="Choose Language"
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={handleAddition}
onChange={handleChange}
/>
);
};
export default DropDownWithHooks;
Working Sandbox

React Native SectionList with columns

I am trying to get a section list shown up having multiple columns.
Since section list have that feature not out of the box, I thought it might be a good idea to render a flatlist for every section item.. but I do not get it to work.
import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { FlatList } from "react-native";
import { SectionList } from "react-native";
class Account extends Component {
data2 =
[
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
data3 =
[
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28adfba',
title: '22--First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91adafa97f63',
title: '22--Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571efadfee29d72',
title: '22--Third Item',
},
];
data4 = ['a', 'b', 'c']
data = [
{sectionTitle: 'test-title-alpha', data: [this.data2]},
{sectionTitle: 'test-title-beta', data: [this.data3]},
];
_renderItem = ({item}) => {
console.log('render-item', item);
return (
<Text>item: {item}</Text>
)
}
_renderSectionHeader = ({item}) => {
console.log('section-header', item);
return (
<Text>section header: {item}</Text>
)
}
_renderSectionListItem = ({item}) => {
console.log('section-list-item', item);
return (
<FlatList
data={item}
numColumns={3}
renderItem={this._renderItem}
//keyExtractor={item => item.id}
/>
)
}
render () {
console.log('render', this.data);
console.log(this.data[0].sectionTitle);
return (
<SectionList
sections={this.data}
renderSectionHeader={this._renderSectionHeader}
renderItem={this._renderSectionListItem}
//keyExtractor={item => item.id}
/>
)
}
}
export default Account;
using data4 seems to proceed, using data2 or data3 seems not.
Anybody see my failure(s)?
Final output should be somethink near to:
first-section-title
item1.id item2.id item3.id
item1.title item2.title item3.title
item1.whatever item2.whatever item3.whatever
second-section-title
item4.id item5.id item6.id
item4.title item5.title item6.title
item4.whatever item5.whatever item6.whatever
...
(grid view, with x items per row)
from source
data = [
{
sectionTitle: 'first-section-title',
data: [
[
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d43',
title: 'and so on',
},
]
]
},
{
sectionTitle: 'second-section-title',
data: [
[
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: '5 Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: '6 Item',
},
]
]
},
];
working example (if somebody else should although need it)
import React, { Component } from 'react';
import { Text, View, FlatList, SectionList } from "react-native"
const sections = [
{
title: "Vegetables",
key: "vegetables",
data: [
{
list: [
{
name: "Carrot",
color: "Orange",
},
{
name: "Cabbage",
color: "Purple",
},
],
},
],
},
{
title: "Fruits",
key: "fruits",
data: [
{
list: [
{
name: "Apple",
color: "Green",
},
{
name: "Banana",
color: "Yellow",
},
{
name: "Strawberry",
color: "Red",
},
{
name: "Blueberry",
color: "Blue",
},
],
},
],
},
]
class Account extends Component {
renderSection = ({ item }) => {
return (
<FlatList
data={item.list}
numColumns={2}
renderItem={this.renderListItem}
keyExtractor={this.keyExtractor}
/>
)
}
renderSectionHeader = ({ section }) => {
return <Text>{section.title}</Text>
}
renderListItem = ({ item }) => {
return (
<View style={{height: 50, width: 100, borderColor: "green", borderWidth: 1 }}>
<Text>{item.name}</Text>
<Text>{item.color}</Text>
</View>
)
}
keyExtractor = (item) => {
return item.name
}
render () {
return (
<SectionList
sections={sections}
renderSectionHeader={this.renderSectionHeader}
renderItem={this.renderSection}
/>
)
}
}
export default Account;

How to add SrNo (#) column at first position at mui-datatable React.js

Created table using React and MUI-Datatables: need to add SrNo column at first, also need to add Delete and IsActive button.
import React, { useState, useEffect } from 'react';
import Grid from '#material-ui/core/Grid';
import Switch from '#material-ui/core/Switch';
import MUIDataTable from "mui-datatables";
export const Services = () => {
const [itemList, setItemList] = useState([]);
const [mainColumns, setMainColumns] = useState([]);
const selectData = async () => {
const response = await ServiceAPI(); // data from web wervice
var data = JSON.parse(response.data);
setItemList(data);
};
const createColumns = () => {
var columns = [];
// how to add Sr No column
columns.push(
{
label: 'ID',
name: 'service_id',
});
columns.push(
{
label: 'Name',
name: 'service_name',
});
setMainColumns(columns);
};
useEffect(() => {
createColumns();
selectData();
}, []);
return (
<>
<h3>Service</h3>
<Grid container >
<Grid item xs={12}>
<MUIDataTable
title={"Service"}
data={itemList}
columns={mainColumns}
className="table nowrap"
/>
</Grid>
</Grid>
</>
);
}
tried below code for active/deactivate, but OnChange() is run every time, which should call on only click event (also tried OnClick()):
columns.push(
{
label: 'Active',
name: 'is_active',
options: {
filter: false,
sort: false,
customBodyRender: (value, tableMeta, updateValue) => {
const serviceID = tableMeta.rowData[0];
return (
<Switch color="primary" checked={value} value={value} onChange={activate}/>
/>
);
}
}
});
Please check example. I have added serial number and delete button in this example.
import React from "react";
import ReactDOM from "react-dom";
import MUIDataTable from "mui-datatables";
import IconButton from "#material-ui/core/IconButton";
import Button from "#material-ui/core/Button";
export default class MuiDatatableSerial extends React.Component {
render() {
const columns = [
{name: "sl", label: "Serial No"},
{name: "name", label: "Name"},
{name: "title", label: "Title"},
{name: "location", label: "Location"},
{name: "age", label: "Age"},
{name: "salary", label: "Salary"},
{
name: "delete",
label: "",
options: {
filter: false,
sort: false,
customBodyRender: (value, tableMeta, updateValue) => {
return <Button
color="secondary"
onClick={(ev) =>
alert('deleted')
}> Delete
</Button>;
},
}
}
];
const data = [
{name: "Khabir Uddin", title: "Senior Software Engineer", location: "Dhaka", age: 38, salary: "$150,000"},
{name: "Gabby George", title: "Business Analyst", location: "Minneapolis", age: 30, salary: "$100,000"},
{name: "Aiden Lloyd", title: "Business Consultant", location: "Dallas", age: 55, salary: "$200,000"}
];
let newData = [];
data.map((item, index) => {
newData.push({sl: index + 1, ...item});
});
const options = {
selectableRows: "none",
onRowsSelect: (rowsSelected, allRows) => {
},
};
return (
<MUIDataTable
title={"ACME Employee list"}
data={newData}
columns={columns}
options={options}
/>
);
}
}

Resources