i'm new to react and i'm trying to convert this class based component to a functionnal component but i get an error of state, how can i convert it please ?
This is my components :)
sandbox link
Thank you
In this example, it is quite straight forward as there are no component life cycle methods. You can just define all the methods in the function, and return the component.
function Demo() {
const [state, setState] = React.useState({
expandedKeys: [],
autoExpandParent: true,
checkedKeys: [],
allCheckedKeys: [],
selectedKeys: [],
newTreeView: false,
newTreeData: []
});
const onExpand = (expandedKeys) => {
console.log("onExpand", expandedKeys);
// if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded children keys.
setState({
...state,
expandedKeys,
autoExpandParent: false
});
};
const onCheck = (checkedKeys, e) => {
const allCheckedKeys = [...checkedKeys, ...e.halfCheckedKeys];
console.log("onCheck", allCheckedKeys);
console.log(createNewTreeData(treeData, allCheckedKeys));
setState((prevState) => ({
...prevState,
allCheckedKeys,
checkedKeys
}));
};
const onSelect = (selectedKeys, info) => {
console.log("onSelect", info);
setState({ ...state, selectedKeys });
};
const renderTreeNodes = (data) =>
data.map((item) => {
if (item.children) {
return (
<TreeNode title={item.title} key={item.key} dataRef={item}>
{renderTreeNodes(item.children)}
</TreeNode>
);
}
return <TreeNode {...item} />;
});
const createTree = () => {
setState((prevState) => ({
...prevState,
newTreeView: true,
newTreeData: createNewTreeData(treeData, prevState.allCheckedKeys)
}));
};
return (
<>
<Tree
checkable
onExpand={onExpand}
expandedKeys={state.expandedKeys}
autoExpandParent={state.autoExpandParent}
onCheck={onCheck}
checkedKeys={state.checkedKeys}
onSelect={onSelect}
selectedKeys={state.selectedKeys}
>
{renderTreeNodes(treeData)}
</Tree>
<button onClick={createTree}>Validate</button>
{state.newTreeView && <Tree>{renderTreeNodes(state.newTreeData)}</Tree>}
</>
);
}
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Tree } from 'antd';
const treeData = [
{
title: '0-0',
key: '0-0',
children: [
{
title: '0-0-0',
key: '0-0-0',
children: [
{
title: '0-0-0-0',
key: '0-0-0-0',
},
{
title: '0-0-0-1',
key: '0-0-0-1',
},
{
title: '0-0-0-2',
key: '0-0-0-2',
},
],
},
{
title: '0-0-1',
key: '0-0-1',
children: [
{
title: '0-0-1-0',
key: '0-0-1-0',
},
{
title: '0-0-1-1',
key: '0-0-1-1',
},
{
title: '0-0-1-2',
key: '0-0-1-2',
},
],
},
{
title: '0-0-2',
key: '0-0-2',
},
],
},
{
title: '0-1',
key: '0-1',
children: [
{
title: '0-1-0-0',
key: '0-1-0-0',
},
{
title: '0-1-0-1',
key: '0-1-0-1',
},
{
title: '0-1-0-2',
key: '0-1-0-2',
},
],
},
{
title: '0-2',
key: '0-2',
},
];
const Demo = () => {
const [expandedKeys, setExpandedKeys] = useState(['0-0-0', '0-0-1']);
const [checkedKeys, setCheckedKeys] = useState(['0-0-0']);
const [selectedKeys, setSelectedKeys] = useState([]);
const [autoExpandParent, setAutoExpandParent] = useState(true);
const onExpand = (expandedKeysValue) => {
console.log('onExpand', expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded children keys.
setExpandedKeys(expandedKeysValue);
setAutoExpandParent(false);
};
const onCheck = (checkedKeysValue) => {
console.log('onCheck', checkedKeysValue);
setCheckedKeys(checkedKeysValue);
};
const onSelect = (selectedKeysValue, info) => {
console.log('onSelect', info);
setSelectedKeys(selectedKeysValue);
};
return (
<Tree
checkable
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onCheck={onCheck}
checkedKeys={checkedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={treeData}
/>
);
};
ReactDOM.render(<Demo />, document.getElementById('container'));
I have updated the code using ES6 arrow functions resulting in shorter and simpler code than traditional functional components.
import React,{useState} from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Tree } from "antd";
const { TreeNode } = Tree;
const treeData = [
{
title: "0-0",
key: "0-0",
children: [
{
title: "0-0-0",
key: "0-0-0",
children: [
{ title: "0-0-0-0", key: "0-0-0-0" },
{ title: "0-0-0-1", key: "0-0-0-1" },
{ title: "0-0-0-2", key: "0-0-0-2" }
]
},
{
title: "0-0-1",
key: "0-0-1",
children: [
{ title: "0-0-1-0", key: "0-0-1-0" },
{ title: "0-0-1-1", key: "0-0-1-1" },
{ title: "0-0-1-2", key: "0-0-1-2" }
]
},
{
title: "0-0-2",
key: "0-0-2"
}
]
},
{
title: "0-1",
key: "0-1",
children: [
{ title: "0-1-0-0", key: "0-1-0-0" },
{ title: "0-1-0-1", key: "0-1-0-1" },
{ title: "0-1-0-2", key: "0-1-0-2" }
]
},
{
title: "0-2",
key: "0-2"
}
];
const createNewTreeData = (treeData, checkedKeys) => {
return treeData.reduce((acc, treeDataItem) => {
if (checkedKeys.includes(treeDataItem.key)) {
if (treeDataItem.children) {
acc.push({
...treeDataItem,
children: createNewTreeData(treeDataItem.children, checkedKeys)
});
} else {
acc.push(treeDataItem);
}
}
return acc;
}, []);
};
const Demo =()=> {
const [state,setState] = useState({
expandedKeys: [],
autoExpandParent: true,
checkedKeys: [],
allCheckedKeys: [],
selectedKeys: [],
newTreeView: false,
newTreeData: []
});
const onExpand = (expandedKeys) => {
console.log("onExpand", expandedKeys);
// if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded children keys.
setState({
expandedKeys,
autoExpandParent: false
});
};
const onCheck = (checkedKeys, e) => {
const allCheckedKeys = [...checkedKeys, ...e.halfCheckedKeys];
console.log("onCheck", allCheckedKeys);
console.log(createNewTreeData(treeData, allCheckedKeys));
setState((prevState) => ({
...prevState,
allCheckedKeys,
checkedKeys
}));
};
const onSelect = (selectedKeys, info) => {
console.log("onSelect", info);
setState({ selectedKeys });
};
const renderTreeNodes = (data) =>
data.map((item) => {
if (item.children) {
return (
<TreeNode title={item.title} key={item.key} dataRef={item}>
{renderTreeNodes(item.children)}
</TreeNode>
);
}
return <TreeNode {...item} />;
});
const createTree = () => {
setState((prevState) => ({
...prevState,
newTreeView: true,
newTreeData: createNewTreeData(treeData, prevState.allCheckedKeys)
}));
};
return (
<>
<Tree
checkable
onExpand={onExpand}
expandedKeys={state.expandedKeys}
autoExpandParent={state.autoExpandParent}
onCheck={onCheck}
checkedKeys={state.checkedKeys}
onSelect={onSelect}
selectedKeys={state.selectedKeys}
>
{renderTreeNodes(treeData)}
</Tree>
<button onClick={createTree}>Validate</button>
{state.newTreeView && (
<Tree>{renderTreeNodes(state.newTreeData)}</Tree>
)}
</>
);
}
ReactDOM.render(<Demo />, document.getElementById("container"));
Related
My goal is that when user select a checkbox of one of the fathers ('Non Veg Biryanis','Pizzas','Drinks','Deserts') in the flatlist, then those sons who belong to him are also selected.
When the check box is removed from all the children belonging to the same father, then the check box is also removed for the father as well.
this is my example (but its not works as can see, the father 'Pizzas' not checked but his sons checked)
The data is:
[
{
title: 'Non Veg Biryanis',
checked: false,
data: [
{ key: 'chicken', value: false, checked: false },
{ key: 'meat', value: false, checked: false },
{ key: 'veg', value: false, checked: false },
],
},
{
title: 'Pizzas',
checked: false,
data: [
{ key: 'olives', value: false, checked: false },
{ key: 'green cheese', value: false, checked: false },
{ key: 'paprika', value: false, checked: false },
],
},
{
title: 'Drinks',
checked: false,
data: [
{ key: 'cola', value: false, checked: false },
{ key: 'sprite', value: false, checked: false },
{ key: 'orange', value: false, checked: false },
],
},
{
title: 'Deserts',
checked: false,
data: [
{ key: 'cake', value: false, checked: false },
{ key: 'ice-cream', value: false, checked: false },
{ key: 'pie', value: false, checked: false },
],
},
]
The Accordian:
import React, { useState } from 'react';
import { View, TouchableOpacity, Text, FlatList, LayoutAnimation, Platform, UIManager } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import styles from './AccordianStyle';
const Accordian = props => {
const [data, setData] = useState(props.item);
const [expanded, setExpanded] = useState(false);
if (Platform.OS === 'android') {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
const onClick = (index: number) => {
console.log(data);
const temp = { ...data };
temp.data[index].checked = !temp.data[index].checked;
setData(temp);
};
const onClickFather = () => {
const temp = { ...data };
temp.checked = !temp.checked;
if (temp.checked) {
temp.data = temp.data.map((item: { checked: boolean }) => {
item.checked = true;
});
}
console.log(temp);
setData(temp);
};
const toggleExpand = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setExpanded(!expanded);
};
return (
<View>
<View style={styles.row}>
<TouchableOpacity onPress={() => onClickFather()}>
<Icon name={'check-circle'} size={24} color={data.checked ? 'green' : '#d3d7de'} />
</TouchableOpacity>
<Text style={[styles.title]}>{data.title}</Text>
<TouchableOpacity style={styles.row} onPress={() => toggleExpand()}>
<Icon name={expanded ? 'keyboard-arrow-up' : 'keyboard-arrow-down'} size={30} color={'grey'} />
</TouchableOpacity>
</View>
<View style={styles.parentHr} />
{expanded && (
<View style={{}}>
<FlatList
data={data.data}
numColumns={1}
scrollEnabled={false}
renderItem={({ item, index }) => (
<View>
<TouchableOpacity
style={[styles.childRow, styles.button, item.checked ? styles.btnActive : styles.btnInActive]}
onPress={() => onClick(index)}
>
<Text style={[styles.itemInActive]}>{item.key}</Text>
<Icon name={'check-circle'} size={24} color={item.checked ? 'green' : '#d3d7de'} />
</TouchableOpacity>
<View style={styles.childHr} />
</View>
)}
/>
</View>
)}
</View>
);
};
export default Accordian;
Modify your onClick function so that it loops through each entry in the data array with the some() method and check if any of the children (sons) are clicked.
If one of them is, then update set the checked property accordingly.
const onClick = (index: number) => {
setData(prevState => {
const newData = prevState.data.map((entry, entryIndex) =>
index === entryIndex ?
({ ...entry, checked: !entry.checked }) :
entry
);
const isAnyChildChecked = newData.some(({ checked }) =>
checked === true
);
return ({
...prevState,
checked: isAnyChildChecked,
data: newData
})
});
};
If the parent is clicked, then check or uncheck all the children as well.
const onClickFather = () => {
setData(prevState => {
const isParentChecked = !prevState.checked;
return ({
...prevState,
checked: isParentChecked,
data: prevState.data.map(item => ({ ...item, checked: isParentChecked }))
});
});
};
I have this component which is a filter for a table..
handleSearch function is responsible to update const filters... its work perfectly when dataIndex props is the same, but when it changes, filters value is backing to it's initial value, an empty array.
I can't manage to resolve it, I've already console log everything.
import React, { useState, } from "react";
import { SearchOutlined } from "#ant-design/icons";
import { Select, Button, Space } from "antd";
const TableFilter = (props) => {
const {
filterType,
filterMode,
filterOptions,
FilterSelectOnFocus,
dataIndex,
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
} = props;
const [filters, setFilters] = useState([]);
const SelectFilter = (
<Select
style={{ width: 188, marginBottom: 8, display: "block" }}
type={filterType}
mode={filterMode}
name={dataIndex}
value={selectedKeys}
optionFilterProp="children"
placeholder={`Search ${dataIndex}`}
onFocus={FilterSelectOnFocus}
showSearch
onChange={(value) => setSelectedKeys(value ? value : [])}
getPopupContainer={(trigger) => trigger}
notFoundContent
>
{filterOptions?.map((type, key) => (
<Select.Option value={type.value} key={key}>
{type.label}
</Select.Option>
))}
</Select>
);
const defaultFilterTypes = [
{
type: "select",
element: SelectFilter,
},
];
const handleFilterType = () => {
const type = defaultFilterTypes.find((types) => types.type === filterType);
return type.element;
};
const handleSearch = () => {
console.log(filters) //is empty when dataIndex value change, when it's is the same it get the update value of the 75 line
confirm();
const newFilterValues = [...filters]
const index = newFilterValues.findIndex(newValue => newValue.searchedColumn === dataIndex)
if(index === -1){
newFilterValues.push({ searchText: selectedKeys, searchedColumn: dataIndex})
}
else{
newFilterValues[index] = {searchText: selectedKeys, searchedColumn: dataIndex}
}
setFilters(newFilterValues)
}
const handleReset = () => {
console.log('reset');
clearFilters();
setFilters({ searchText: "" });
setSelectedKeys([]);
};
return (
<div style={{ padding: 8 }}>
{handleFilterType()}
<Space>
<Button
type="primary"
onClick={() => handleSearch()}
icon={<SearchOutlined />}
size="small"
style={{ width: 90 }}
>
Search
</Button>
<Button
onClick={() => handleReset()}
size="small"
style={{ width: 90 }}
>
Reset
</Button>
</Space>
</div>
);
};
export default TableFilter;
Table Component
import React, { useEffect, useState } from "react";
import { Table } from "antd";
import { getTransactions } from "../../../../api/Transactions";
import { formatCnpjCpf, formatCurrency } from "../../../../utils/masks";
import TableFilter from "../../../../shared-components/ant-design/containers/TableFilters";
import { getPartnersAsOptions } from "../../../../api/Partners";
const Insider = (props) => {
const [data, setData] = useState([]);
const [paginationValues, setPaginationValues] = useState({
current: 1,
pageSize: 50,
total: 0,
position: ["topRight"],
});
const [partners, setPartners] = useState([{value: null, label: 'carregando...'}])
const context = "insider";
function getColumnSearchProps(
dataIndex,
filterType,
filterMode,
filterOptions,
FilterSelectOnFocus
) {
return {
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters,
}) => {
return (
<TableFilter
dataIndex={dataIndex}
filterType={filterType}
filterMode={filterMode}
filterOptions={filterOptions}
FilterSelectOnFocus={FilterSelectOnFocus}
setSelectedKeys={setSelectedKeys}
selectedKeys={selectedKeys}
confirm={confirm}
clearFilters={clearFilters}
/>
);
},
};
}
async function getPartners(){
if(partners.length > 2){
return
}
const response = await getPartnersAsOptions(paginationValues)
setPartners(response.data)
}
const columns = [
{
dataIndex: ["transactionType", "desc"],
title: "Tipo de Transação",
sorter: true,
key: "orderTransactionType",
...getColumnSearchProps("orderTransactionType"),
},
{
dataIndex: "transactionDate",
title: "Data Transação",
key: "orderTransactionDate",
sorter: true,
...getColumnSearchProps("orderTransactionDate"),
},
{
title: "Nome origem",
dataIndex: ["source", "name"],
sorter: true,
key: "orderSourceCustomerName",
},
{
render: (render) => formatCnpjCpf(render.source.document.value),
title: "Documento origem",
key: "sourceCustomer",
...getColumnSearchProps("sourceCustomer", "select", "tags")
},
{
title: "Nome destino",
dataIndex: ["target", "name"],
sorter: true,
key: "orderTargetCustomerName",
},
{
render: (render) => formatCnpjCpf(render.target.document.value),
title: "Documento destino",
},
{
render: (render) => formatCurrency(render.value),
title: "Valor da transação",
key: "orderValue",
sorter: true,
align: "right",
},
{
render: (render) => formatCurrency(render.chargedTariff),
title: "Tarifa",
key: "orderChargedTariff",
sorter: true,
align: "right",
},
{
render: (render) => formatCurrency(render.cost),
title: "Custo",
key: "orderCost",
sorter: true,
align: "right",
},
{
render: (render) => formatCurrency(render.revenue),
title: "Receita",
key: "orderRevenue",
sorter: true,
align: "right",
},
{
title: "Parceiro",
name: "Parceiro",
dataIndex: ["partner", "name"],
key: "orderPartnerName",
sorter: true,
align: "center",
...getColumnSearchProps(
"orderPartnerName",
"select",
"multiple",
partners,
getPartners)
},
{
title: "id da transação",
name: "id da transação",
dataIndex: "id",
},
];
useEffect(function transactions() {
async function fetchTransactions() {
const response = await getTransactions(context, paginationValues);
if (response) {
const { data, pagination } = response;
setData(data);
setPaginationValues(pagination);
}
}
fetchTransactions();
// eslint-disable-next-line
}, []);
return <Table dataSource={data} columns={columns} />;
};
export default Insider;
You could move this piece of code
const [filters, setFilters] = useState([]);
In a higher level
I am using react table v6 for grid purposes. I am trying to implement a subcomponent where in the data to this sub component needs to be passed dynamically. This sub component should expand and collapse on click of arrows. I have tried the following , but the sub component is not rendering any data. I am creating a wrapper for this, the data to the subcomponent should be passed dynamically based on the source data.
https://codesandbox.io/s/react-table-row-table-subcompoentn-sk14i?file=/src/DataGrid.js
import * as React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";
export default class DataGrid extends React.Component {
renderSubComponent = original => {
console.log(original);
return (
original.nested &&
original.nested.map((i, key) => (
<React.Fragment key={key}>
<div>{i.name}</div>
<div>{i.value}</div>
</React.Fragment>
))
);
};
render() {
return (
<ReactTable
data={this.props.data}
columns={this.props.columns}
SubComponent={this.renderSubComponent}
/>
);
}
}
import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
columns: [],
allData: []
};
}
componentDidMount() {
this.getData();
this.getColumns();
}
getData = () => {
const data = [
{
firstName: "Jack",
status: "Submitted",
nested: [
{
name: "test1",
value: "NA"
},
{
name: "test2",
value: "NA"
}
],
age: "14"
},
{
firstName: "Simon",
status: "Pending",
nested: [
{
name: "test3",
value: "NA"
},
{
name: "test4",
value: "Go"
}
],
age: "15"
}
];
this.setState({ data });
};
getColumns = () => {
const columns = [
{
Header: "First Name",
accessor: "firstName"
},
{
Header: "Status",
accessor: "status"
},
{
Header: "Age",
accessor: "age"
}
];
this.setState({ columns });
};
onClickRow = rowInfo => {
this.setState({ allData: rowInfo }, () => {
console.log(this.state.allData);
});
};
render() {
return (
<>
<DataGrid
data={this.state.data}
columns={this.state.columns}
rowClicked={this.onClickRow}
/>
</>
);
}
}
render(<App />, document.getElementById("root"));
try spread the argument and it will work :
...
renderSubComponent = ({original}) => {
...
I'm using the react-sortablejs library.
When trying to move cards within the list. I get the error:
Cannot read property 'map' of undefined
I have a dense structure and it gets lost here. How to handle onChange so that I can see in the console that the order of the notes within the list has changed.
Demo here
import Sortable from 'react-sortablejs';
// Functional Component
const SortableList = ({ items, onChange }) => {
return (
<div>
<Sortable
tag="ul"
onChange={(order, sortable, evt) => {
console.log(order)
onChange(order);
}}
>
{items.listItems.map(val => {
return <li key={uniqueId()} data-id={val}>List Item: {val.title}</li>})
}
</Sortable>
</div>
);
};
class App extends React.Component {
state = {
item: {
id: "abc123",
name: "AAA",
lists: [
{
id: "def456",
list_id: "654wer",
title: 'List1',
desc: "description",
listItems: [
{
id: "ghj678",
title: "ListItems1",
listItemsId: "88abf1"
},
{
id: "poi098",
title: "ListItems2",
listItemsId: "2a49f25"
},
{
id: "1oiwewedf098",
title: "ListItems3",
listItemsId: "1a49f25dsd8"
}
]
},
{
id: "1ef456",
list_id: "654wer",
title: 'List 2',
desc: "description",
listItems: [
{
id: "1hj678",
title: "ListItems4",
listItemsId: "18abf1"
},
{
id: "1oi098",
title: "ListItems5",
listItemsId: "1a49f25"
},
{
id: "1oiwewe098",
title: "ListItems6",
listItemsId: "1a49f25dsd"
}
]
},
{
id: "2ef456",
title: 'List 3',
list_id: "254wer",
desc: "description",
listItems: [
{
id: "2hj678",
title: "ListItems7",
listItemsId: "28abf1"
},
{
id: "2oi098",
title: "ListItems8",
listItemsId: "234a49f25"
},
{
id: "df098",
title: "ListItems9",
listItemsId: "1asd8"
}
]
}
]
}
};
render() {
const c = this.state.item['lists'].map(item => { return item.listItems});
return (
this.state.item['lists'].map(item => {
return (<div>
{item.title}
<SortableList
key={uniqueId()}
items={item}
onChange={(item) => {
console.log(item)
this.setState({item});
}}
>
</SortableList>
</div>)
})
)
}
};
Thanks in advance.
You have to update few changes in your code.
Update the SortableList function as below.
First pass data-id={val.id} in li and after that in onChange method you will receive the order with id. So based on that we are sorting the records.
const SortableList = ({ items, onChange }) => {
return (
<div>
<Sortable
tag="ul"
onChange={(order, sortable, evt) => {
items.listItems.sort(function(a, b){
return order.indexOf(a.id) - order.indexOf(b.id);
});
onChange(items);
}}
>
{items.listItems.map(val => {
return <li key={uniqueId()} data-id={val.id}>List Item: {val.title}</li>})
}
</Sortable>
</div>
);
};
Update the onChange event of App component.
onChange={(item) => {
let itemObj = {...this.state.item};
itemObj.lists.map(x=>{
if(x.id === item.id) x = item;
});
this.setState({itemObj});
}}
That's it!
Here is the working demo for you
https://stackblitz.com/edit/react-sortablejs-blzxwd
When remove the onChange event in the Sortable list, Its works.
const SortableList = ({ items, onChange }) => {
return (
<div>
<Sortable
tag="ul"
>
{items.listItems.map(val => {
return <li key={uniqueId()} data-id={val}>List Item: {val.title}</li>})
}
</Sortable>
</div>
);
};
https://codesandbox.io/s/8x331yomp0
I'm trying to create a select all checkbox in my table. When I click the header checkbox, I want the other checkboxes to populate, as well.
I'm trying to do this with a selectAlll state value, but for whatever reason, this keeps coming back false the first time, so it is always opposite of what the value should be. Any chance someone knows what is wrong? I put the code sandbox up at the top, but here is my table code:
import React, { Component } from "react";
import $ from "jquery";
import ReactTable from "react-table";
import "react-table/react-table.css";
const style = {
container: {
position: "relative"
},
refresh: {
cursor: "pointer",
width: "75px"
}
};
class KKTable extends Component {
constructor() {
super();
this.state = {
loading: true,
timestamp: "",
selectAll: false,
data: [],
checked: []
};
this.handleChange = this.handleChange.bind(this);
}
handleChange = () => {
var selectAll = !this.state.selectAll;
this.setState({ selectAll: selectAll });
var checkedCopy = [];
this.state.data.forEach(function(e, index) {
checkedCopy.push(selectAll);
});
};
componentDidMount() {
const data2 = [
{ one: "hi0", two: "two0", three: "three0" },
{ one: "hi1", two: "two1", three: "three1" },
{ one: "hi2", two: "two2", three: "three2" },
{ one: "hi3", two: "two3", three: "three3" },
{ one: "hi4", two: "two4", three: "three4" },
{ one: "hi5", two: "two5", three: "three5" },
{ one: "hi6", two: "two6", three: "three6" },
{ one: "hi7", two: "two7", three: "three7" },
{ one: "hi8", two: "two8", three: "three8" }
];
var checkedCopy = [];
var selectAll = this.state.selectAll;
data2.forEach(function(e, index) {
checkedCopy.push(selectAll);
});
this.setState({
data: data2,
checked: checkedCopy,
selectAll: false
});
}
render() {
return (
<div>
<div className="container">
<ReactTable
data={this.state.data}
filterable
defaultFilterMethod={(filter, row) =>
row[filter.id] !== undefined
? String(row[filter.id])
.toLowerCase()
.includes(filter.value.toLowerCase())
: false
}
columns={[
{
Header: "One",
accessor: "one"
},
{
Header: <input type="checkbox" onChange={this.handleChange} />,
Cell: row => (
<input
type="checkbox"
defaultChecked={this.state.checked[row.index]}
/>
),
sortable: false,
filterable: false
},
{
Header: "Two",
accessor: "two"
},
{
Header: "Three",
accessor: "three"
}
]}
className="-striped "
/>
</div>
</div>
);
}
}
export default KKTable;
Figured it out. In case anyone needs the code:
import React, { Component } from "react";
import $ from "jquery";
import ReactTable from "react-table";
import "react-table/react-table.css";
const style = {
container: {
position: "relative"
},
refresh: {
cursor: "pointer",
width: "75px"
}
};
class KKTable extends Component {
constructor() {
super();
this.state = {
loading: true,
timestamp: "",
selectAll: false,
data: [],
checked: []
};
this.handleChange = this.handleChange.bind(this);
this.handleSingleCheckboxChange = this.handleSingleCheckboxChange.bind(
this
);
}
handleChange = () => {
var selectAll = !this.state.selectAll;
this.setState({ selectAll: selectAll });
var checkedCopy = [];
this.state.data.forEach(function(e, index) {
checkedCopy.push(selectAll);
});
this.setState({
checked: checkedCopy
});
};
handleSingleCheckboxChange = index => {
console.log(index);
var checkedCopy = this.state.checked;
checkedCopy[index] = !this.state.checked[index];
if (checkedCopy[index] === false) {
this.setState({ selectAll: false });
}
this.setState({
checked: checkedCopy
});
};
componentDidMount() {
const data2 = [
{ one: "hi0", two: "two0", three: "three0" },
{ one: "hi1", two: "two1", three: "three1" },
{ one: "hi2", two: "two2", three: "three2" },
{ one: "hi3", two: "two3", three: "three3" },
{ one: "hi4", two: "two4", three: "three4" },
{ one: "hi5", two: "two5", three: "three5" },
{ one: "hi6", two: "two6", three: "three6" },
{ one: "hi7", two: "two7", three: "three7" },
{ one: "hi8", two: "two8", three: "three8" }
];
var checkedCopy = [];
var selectAll = this.state.selectAll;
data2.forEach(function(e, index) {
checkedCopy.push(selectAll);
});
this.setState({
data: data2,
checked: checkedCopy,
selectAll: selectAll
});
}
render() {
console.log(this.state);
return (
<div>
<div className="container">
<ReactTable
data={this.state.data}
filterable
defaultFilterMethod={(filter, row) =>
row[filter.id] !== undefined
? String(row[filter.id])
.toLowerCase()
.includes(filter.value.toLowerCase())
: false
}
columns={[
{
Header: "One",
accessor: "one"
},
{
Header: (
<input
type="checkbox"
onChange={this.handleChange}
checked={this.state.selectAll}
/>
),
Cell: row => (
<input
type="checkbox"
defaultChecked={this.state.checked[row.index]}
checked={this.state.checked[row.index]}
onChange={() => this.handleSingleCheckboxChange(row.index)}
/>
),
sortable: false,
filterable: false
},
{
Header: "Two",
accessor: "two"
},
{
Header: "Three",
accessor: "three"
}
]}
className="-striped "
/>
</div>
</div>
);
}
}
export default KKTable;
Where are you pulling the filter.id from in row[filter.id] !== undefined?
This may cause some issues with how the child items are then selected