score:1
Accepted answer
Something really went wrong with your code (or homework i guess?)
Please have a look at least at the docs for React.useState to set some basics.
First you should init your initalColumns
and later you should filter on them.
Additional i init the checkColumns
with the correct values and changed the wrong logic for changing them.
Have a look how the filtering is done via Array.includes maybe someone will ask for this ;-)
Another point is that you may split the state object in separate primitive states.
Nevertheless here is a working stackblitz and the depending code.
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Button, Dropdown, Menu, Checkbox } from 'antd';
const App = () => {
const columns = [
{
title: 'Description',
dataIndex: 'description',
},
{
title: 'Employees',
dataIndex: 'employees',
},
];
const [colmenu, setColmenu] = React.useState({
value: false,
checkedColumns: ['description', 'employees'],
visibleMenuSettings: false,
columns,
initialColumns: columns,
});
const onChange = (e) => {
let { checkedColumns, columns, initialColumns } = colmenu;
if (!e.target.checked) {
checkedColumns = checkedColumns.filter((id) => {
return id !== e.target.id;
});
console.log('if checked columns is', checkedColumns);
} else if (e.target.checked) {
checkedColumns.push(e.target.id);
console.log('elseif checked columns', checkedColumns);
}
console.log(columns);
columns = initialColumns.filter((col) =>
checkedColumns.includes(col.dataIndex)
);
setColmenu({ ...colmenu, columns, checkedColumns });
};
const handleVisibleChange = (flag) => {
setColmenu({ ...colmenu, visibleMenuSettings: flag });
};
const menu = (
<Menu>
<Menu.ItemGroup title="Columns">
<Menu.Item key="0">
<Checkbox id="description" onChange={onChange} defaultChecked>
Description
</Checkbox>
</Menu.Item>
<Menu.Item key="1">
<Checkbox id="employees" onChange={onChange} defaultChecked>
Employees
</Checkbox>
</Menu.Item>
</Menu.ItemGroup>
</Menu>
);
const dataSource = [
{
key: '1',
description: 'Holiday 1',
employees: '79',
},
{
key: '2',
description: 'Holiday 2',
employees: '12',
},
{
key: '3',
description: 'Holiday 3',
employees: '0',
},
];
return (
<div>
<div className="row">
<div className="col-12 mb-3 d-flex justify-content-end align-items-center">
<Dropdown
overlay={menu}
onVisibleChange={handleVisibleChange}
visible={colmenu.visibleMenuSettings}
>
<Button>Show/Hide Columns</Button>
</Dropdown>
</div>
</div>
<div className="row">
<div className="col-12">
<Table
columns={colmenu.columns}
dataSource={dataSource}
size="small"
pagination={{
pageSizeOptions: ['20', '50'],
showSizeChanger: true,
}}
/>
</div>
</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('container'));
Source: stackoverflow.com
Related Query
- React JS Filter Methods: Hiding table columns using array filters and state
- Testing changes to React component state and spying on instance methods using enzyme
- how to filter all columns of html table using react js?
- filter and replace array state using setState not working
- How Use images from javascript array in react using filter and map function
- Filter an array every time a function is executed and my react state change
- Keep URL and state when working with filter drop-downs using react hook
- Want to populate dynamic data for rows and columns from state in Collapsible table using material UI for React.js
- React - filter nested array and update the state
- How to set and access values of nested array objects in React state using useState hook?
- Using methods and rerendering React Components in array
- Filter results of array of objects in React, using Filter and state
- Updating and merging state object using React useState() hook
- Typescript and React setting initial state with empty typed array
- Updating the array object in React state using immutability helper
- How to make some columns align left and some column align center in React Table - React
- how to set state array using react hooks
- UI not re-rendering on state update using React Hooks and form submission
- How to use drag and drop functionality both columns and rows in my React Table - ReactJS
- No need for state in React components if using Redux and React-Redux?
- Using ref with React Hooks in Ant design (antd) Table component with customized filters
- how and when to call a react component methods after state change from redux
- synchronise scroll of two react components without using state and actions
- How to make the API call and display it in React JS using React Table and Axios?
- Using React Date Range picker to filter a React table
- My first sample table using react-data-grid, columns are not rendered next to each other, instead they are overlapping over and over each other
- How to filter and sort the same array of object state in redux?
- How do I keep state persistant using local storage, react hooks, and Context Provider
- Manage checkbox state in an infinite scrolling table using React
- React - Combine data returned two api calls and set state of an array with these values
More Query from same tag
- Apollo Server Resolver not returning all data (returned data is not complete)
- Textfields in a Grid not responsive when it is under a tab
- Add / Update Deep Array of Objects in React / Redux
- React how to update style coordinates
- How do i display Breadcrumb name conditionally on response from child.in React with hooks?
- reactjs firebase authentication update profile does not refresh
- How to convert CSS subclass to Styled Component
- Chrome WebSpeech API returning not-allowed error?
- TS Lint Error; Type X is not assignable to type 'IntrinsicAttributes & RefAttributes<any>'
- Regex filter returning object Object instead of element
- React: Searches do not render
- Next.js setting current active class with Link and router
- can't resolve stripe - import axios from axios NEXTJS
- Formik form won't clear out
- Use the updated state in the another function as parameter
- React Moment subtract time format
- Can useParams be able to use inside App.js?
- How to change colors for a button in react-bootstrap?
- Re-usable sidebar with custom content Semantic UI
- React Redux connected component with async action testing
- Update Nested state in reactjs
- Importing css into react js
- React - useEffect
- How to fetch json data in react?
- How to create a function with fixed single argument that ignores callback arguments
- React -> State Management
- How to pass multiple GTM tags in gatsby-plugin-google-tagmanager plugin?
- React and Yii2 connection error - No 'Access-Control-Allow-Origin' header is present on the requested resource
- React - animate mount and unmount of a single component
- Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Search> & Readonly<{ children?: ReactNode; }>