add dataset dynamically to data list not work - reactjs

I'm using the react-csv library and I have an issue.
If I dynamically allocate a dataset and download it through CSVLink, then an empty CSV file is downloaded. but if I use static dataset, it just fine
How do I solve it?
Here is my code
import './App.css';
import { CSVLink } from "react-csv";
import { useState } from 'react';
function App() {
const [data, setData] = useState([])
const headers = [
{ label: "gu", key: "region_2depth_name" },
{ label: "legal_dong", key: "region_3depth_name" },
{ label: "address", key: "address_name" },
{ label: "usage", key: "usage"},
{ label: "lat", key: "lat" },
{ label: "lng", key: "lng" }
];
const addData = () => {
data.push({
region_2depth_name: "gu",
region_3depth_name: "legal_dong",
address_name: "address",
usage: "usage",
lat: "lat",
lng: "lng"
})
}
return (
<div>
onClick={addData}>
Add dataset
</button>
<CSVLink data={data} headers={headers}>
Download me
</CSVLink>;
</div>
);
}
export default App;

You have to use useState hook setData properly to add properly on the data array.
const addData = () => {
setData((oldData) => [
...oldData,
{
region_2depth_name: 'gu',
region_3depth_name: 'legal_dong',
address_name: 'address',
usage: 'usage',
lat: 'lat',
lng: 'lng',
},
]);
};
You can check here for the running code:
https://stackblitz.com/edit/react-84emed?file=src/App.js

Related

Can't save value into database through Reactjs Component

I just start learning Reactjs and I have trouble with Component. Here are my code:
export default function ChonLanguage() {
const [selectedOption, setSelectedOption] = useState([]);
const options = [
{ value: 'Vietnamese', label: 'Vietnamese' },
{ value: 'English', label: 'English' },
{ value: 'Chinese', label: 'Chinese' },
{ value: 'Japanese', label: 'Japanese' },
{ value: 'German', label: 'German' },
];
const handleChangeOption = () => {
return setSelectedOption;
}
return (
<Select className={`col-12 o-languages`}
onChange={handleChangeOption()}
options={options} />
)
}
It shown my options, but when I submit, I not save into Database. What should I change? Thanks
Made some minor changes to your code.
Kindly note:-
setSelectedOption is function of type React.dispatch<[]> which will update selectedOption state value so you need to pass some value in that.
useEffect is used to check the updated value of selectedOption, you may not use it.
export default function ChonLanguage() {
const [selectedOption, setSelectedOption] = useState([]);
const options = [
{ value: "Vietnamese", label: "Vietnamese" },
{ value: "English", label: "English" },
{ value: "Chinese", label: "Chinese" },
{ value: "Japanese", label: "Japanese" },
{ value: "German", label: "German" }
];
const handleChangeOption = (event) => {
return setSelectedOption(event.value);
};
useEffect(() => {
console.log(selectedOption);
}, [selectedOption]);
return (
<Select
className={`col-12 o-languages`}
onChange={(e) => {
handleChangeOption(e);
}}
options={options}
/>
);
}

Antd Tree component, how to add cache data

I have a problem with the Tree component of the Antd library. The problem is presented on the video. Namely that the component after changing the data tree renders anew and after selecting an option the previous ones are cleared. Does anyone have any idea how to solve this, so that after changing the data tree, the previous options that were selected are still selected?
import React, { useState } from 'react';
import { Tree } from 'antd';
import { Wrapper, TreeContainer } from './Tree.styled';
const treeData = [
{
title: '0-1',
key: '0-1',
children: [
{ title: '0-1-0-0', key: '0-0-0-0', },
{ title: '0-1-0-1', key: '0-0-0-1' },
{ title: '0-1-0-2', key: '0-0-0-2' },
],
},
{
title: '0-2',
key: '0-2',
},
{
title: '0-3',
key: '0-3',
children: [
{ title: '0-2-0-0', key: '0-2-0-0', },
{ title: '0-2-0-1', key: '0-2-0-1' },
{ title: '0-2-0-2', key: '0-2-0-2' },
],
},
{
title: '0-4',
key: '0-4',
children: [
{ title: '0-3-0-0', key: '0-3-0-0', },
{ title: '0-3-0-1', key: '0-3-0-1' },
{ title: '0-3-0-2', key: '0-3-0-2' },
],
},
{
title: '0-5',
key: '0-5',
children: [
{ title: '0-4-0-0', key: '0-4-0-0', },
{ title: '0-4-0-1', key: '0-4-0-1' },
{ title: '0-4-0-2', key: '0-4-0-2' },
],
},
];
const AntdTree = () => {
const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
const [optionValue, setOptionValue] = useState<any>();
const tree = treeData.filter(filterValue => filterValue.key == (!!optionValue ? optionValue : filterValue.key)).map(data => data)
const onCheck = (checkedKeysValue: any) => {
console.log('onCheck', checkedKeysValue);
setCheckedKeys(checkedKeysValue);
};
return (
<>
<Wrapper>
<TreeContainer>
<select value={optionValue} onChange={e => setOptionValue(e.target.value)} >
<option value={'0-1'}>0-1</option>
<option value={'0-2'}>0-2</option>
<option value={'0-3'}>0-3</option>
<option value={'0-4'}>0-4</option>
<option value={'0-5'}>0-5</option>
</select>
<button onClick={() => setOptionValue('')} >Delete</button>
<Tree
checkable
onCheck={onCheck}
checkedKeys={checkedKeys}
treeData={tree}
/>
</TreeContainer>
</Wrapper>
</>
);
};
export default AntdTree;
Link to video with problem: https://youtu.be/BLEzQck3cZo
Thanks for your help !😊
onCheck callback in your case rewrite new values. You can save previous values using prevState in useState hook like so:
const onCheck = (checkedKeysValue: React.Key[], info: any) => {
console.log('onCheck', checkedKeysValue);
console.log('info', info);
if (info.checked) { // handle check case
setCheckedKeys(prevState => [...prevState, ...checkedKeysValue]);
} else { // handle uncheck case
setCheckedKeys(checkedKeysValue);
}
};

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

How to select the desired input field for filtering in React Data Grid

I am trying to write some tests using Cypress with Reactjs (both latest versions). It seems like there is nothing I can select these input fields of filtering because they all look the same. Is there a way to put id/class names to these fields? I am both new to React and Cypress. Thanks
https://codesandbox.io/s/w6jvml4v45?from-embed=&file=/src/index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import ReactDataGrid from "react-data-grid";
import { Toolbar, Data } from "react-data-grid-addons";
import createRowData from "./createRowData";
import "./styles.css";
const defaultColumnProperties = {
filterable: true,
width: 120
};
const selectors = Data.Selectors;
const columns = [
{
key: "id",
name: "ID"
},
{
key: "title",
name: "Title"
},
{
key: "firstName",
name: "First Name"
},
{
key: "lastName",
name: "Last Name"
},
{
key: "email",
name: "Email"
},
{
key: "street",
name: "Street"
},
{
key: "zipCode",
name: "ZipCode"
},
{
key: "date",
name: "Date"
},
{
key: "jobTitle",
name: "Job Title"
},
{
key: "catchPhrase",
name: "Catch Phrase"
},
{
key: "jobArea",
name: "Job Area"
},
{
key: "jobType",
name: "Job Type"
}
].map(c => ({ ...c, ...defaultColumnProperties }));
const ROW_COUNT = 50;
const handleFilterChange = filter => filters => {
const newFilters = { ...filters };
if (filter.filterTerm) {
newFilters[filter.column.key] = filter;
} else {
delete newFilters[filter.column.key];
}
return newFilters;
};
function getRows(rows, filters) {
return selectors.getRows({ rows, filters });
}
function Example({ rows }) {
const [filters, setFilters] = useState({});
const filteredRows = getRows(rows, filters);
return (
<ReactDataGrid
columns={columns}
rowGetter={i => filteredRows[i]}
rowsCount={filteredRows.length}
minHeight={500}
toolbar={<Toolbar enableFilter={true} />}
onAddFilter={filter => setFilters(handleFilterChange(filter))}
onClearFilters={() => setFilters({})}
/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Example rows={createRowData(50)} />, rootElement);
I would Use This specific attribute syntax to select them by key value:
cy.get(`input[key="${targetValue}"]`)
.then(element => {
//My code
})

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