Export to CSV button in react table - javascript

Looking for a way to add an "Export to CSV" button to a react-table which is an npmjs package (https://www.npmjs.com/package/react-table).
I need to add a custom button for exporting the table data to an excel sheet in the csv or xls format?

Take a look at this npm library - https://www.npmjs.com/package/react-csv
For example -
import {CSVLink, CSVDownload} from 'react-csv';
const csvData =[
['firstname', 'lastname', 'email'] ,
['John', 'Doe' , 'john.doe#xyz.com'] ,
['Jane', 'Doe' , 'jane.doe#xyz.com']
];
<CSVLink data={csvData} >Download me</CSVLink>
// or
<CSVDownload data={csvData} target="_blank" />

Here is what the integration will look like:
import React from "react";
import "react-dropdown/style.css";
import "react-table/react-table.css";
import ReactTable from "react-table";
import { CSVLink } from "react-csv";
const columns = [
{
Header: "name",
accessor: "name", // String-based value accessors!
},
{
Header: "age",
accessor: "age",
},
];
class AllPostPage extends React.Component {
constructor(props) {
super(props);
this.download = this.download.bind(this);
this.state = {
tableproperties: {
allData: [
{ name: "ramesh", age: "12" },
{ name: "bill", age: "13" },
{ name: "arun", age: "9" },
{ name: "kathy", age: "21" },
],
},
dataToDownload: [],
};
}
download(event) {
const currentRecords = this.reactTable.getResolvedState().sortedData;
var data_to_download = [];
for (var index = 0; index < currentRecords.length; index++) {
let record_to_download = {};
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
record_to_download[columns[colIndex].Header] =
currentRecords[index][columns[colIndex].accessor];
}
data_to_download.push(record_to_download);
}
this.setState({ dataToDownload: data_to_download }, () => {
// click the CSVLink component to trigger the CSV download
this.csvLink.link.click();
});
}
render() {
return (
<div>
<div>
<button onClick={this.download}>Download</button>
</div>
<div>
<CSVLink
data={this.state.dataToDownload}
filename="data.csv"
className="hidden"
ref={(r) => (this.csvLink = r)}
target="_blank"
/>
</div>
<div>
<ReactTable
ref={(r) => (this.reactTable = r)}
data={this.state.tableproperties.allData}
columns={columns}
filterable
defaultFilterMethod={(filter, row) =>
String(row[filter.id])
.toLowerCase()
.includes(filter.value.toLowerCase())
}
/>
</div>
</div>
);
}
}
export default AllPostPage;
This will work with filters as well.

I have it implemented like this in React + Typescript (no dependency):
/**
* #desc get table data as json
* #param data
* #param columns
*/
const getTableDataForExport = (data: any[], columns: any[]) => data?.map((record: any) => columns
.reduce((recordToDownload, column) => (
{ ...recordToDownload, [column.Header]: record[column.accessor] }
), {}));
/**
* #desc make csv from given data
* #param rows
* #param filename
*/
const makeCsv = async (rows: any[], filename: string) => {
const separator: string = ';';
const keys: string[] = Object.keys(rows[0]);
const csvContent = `${keys.join(separator)}\n${
rows.map((row) => keys.map((k) => {
let cell = row[k] === null || row[k] === undefined ? '' : row[k];
cell = cell instanceof Date
? cell.toLocaleString()
: cell.toString().replace(/"/g, '""');
if (cell.search(/("|,|\n)/g) >= 0) {
cell = `"${cell}"`;
}
return cell;
}).join(separator)).join('\n')}`;
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // In case of IE 10+
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
if (link.download !== undefined) {
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
};
the table:
<Table data={data} columns={columns} />
and the button:
<button
type="button"
onClick={() => makeCsv(getTableDataForExport(data, columns), `${filename}.csv`)}
>
Download table data CSV
</button>

I thought I'd piggyback on best wishes' extremely valuable answer with a simplified download implementation.
export = e => {
const currentRecords = this.ReactTable.getResolvedState().sortedData;
this.setState({ dataToDownload: this.dataToDownload(currentRecords, columns) }, () =>
this.csvLink.link.click()
);
}
dataToDownload = (data, columns) =>
data.map(record =>
columns.reduce((recordToDownload, column) => {
recordToDownload[column.Header] = record[column.accessor];
return recordToDownload;
}, {})
);
I used this to allow multiple table exports in one component by adding additional export functions.

Related

How to remove commas from strings in an array?

I need to remove commas which are in an array of odata objects. Each item has a description which sometimes contains commas. I need to remove those commas.
Here is what I've attempted:
Parent Component:
<CSVComponent capxs={allCaps} />
Child Component:
import { CSVLink } from "react-csv";
export interface ICSVComponentProps {
capxs: IListItem[];
}
export const CSVComponent: React.FunctionComponent<ICSVComponentProps> = (props: ICSVComponentProps) => {
const [results, setResults] = React.useState([]);
const headers = [
{ label: "Id", key: "id" },
{ label: "Title", key: "title" },
{ label: "Description", key: "description" },
];
const getCaps = (c: IListItem[]) => {
const results = [];
for (let i = 0; i <= c.length - 1; i++) {
results[i] = {
id: props.capxs[i].Id,
title: props.capxs[i].Title,
description: props.capxs[i].Description.replace(",",""),
};
}
setResults(results);
};
return (
<DefaultButton className={styles.csvButton}
onClick={() => getCaps(props.capxs)}
>
<CSVLink data={results} headers={headers}>
Create CSV
</CSVLink>
</DefaultButton>
);
Update:
I've updated the code sample above with the Parent component props pass down and more of the child component.
Here is an image showing the array that is created and stored in state. This state is then used by react-csv:
The description value in each item in the array has the comma removed, but react-csv seems to ignore this and it detects the commas, therefore creating incorrect columns in the produced csv file.
If I understand correctly what you need
const memoizedCaps = useMemo<IListItem[]>(() => {
return caps.map(el => ({ ...el, description: el.description.replace(',', '') }));
}, [caps]);
const getCaps = () => {
setResults(memoizedCaps);
};
This issue has been resolved by using:
const getCaps = (caps: IListItem[]) => {
const results = [];
for (let i = 0; i <= caps.length - 1; i++) {
results[i] = {
description: props.capxs[i].Description.replace(/,/g, '""'),
};
}
setResults(results);
};
Not ideal but it's a limitation of react-csv.
Ref: https://github.com/react-csv/react-csv/issues/176
Thanks for all your help.

Need to fix a issue that comming in antd tree component

I am using an antd tree component my issue is if you search something in the search bar then you will get search results in that result if you check and up check any field what happens all previous data get unchecked whatever data is present into the search bar result that only data remain selected if it already select or you just select what my task is I don't want to get unchecked all previously selected checked that only field update that we change right now I don't have any idea how can I fix this if anybody knows anyway, also I added a complete code SandBox link below.
This is my search bar filter code
const hasSearchTerm = (n, searchTerm) =>
n.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1;
const filterData = (arr, searchTerm) =>
arr?.filter(
(n) =>
hasSearchTerm(n.title, searchTerm) ||
filterData(n.children, searchTerm)?.length > 0
);
function filteredTreeData(data, searchString, checkedKeys, setExpandedTree) {
let keysToExpand = [];
const filteredData = searchString
? filterData(data, searchString).map((n) => {
keysToExpand.push(n.key);
return {
...n,
children: filterData(n.children, searchString, checkedKeys)
};
})
: data;
setExpandedTree([...keysToExpand]);
return filteredData;
}
This issue happens when the check or unchecks field after searching in the search bar in this part of the code
const onCheck = (checkedKeysValue) => {
console.log("onCheck", checkedKeysValue);
setCheckedKeys(checkedKeysValue);
};
const Demo = () => {
const [expandedKeys, setExpandedKeys] = useState([]);
const [checkedKeys, setCheckedKeys] = useState([]);
const [selectedKeys, setSelectedKeys] = useState([]);
const [autoExpandParent, setAutoExpandParent] = useState(true);
const [searchValue, setSearchValue] = useState("");
const [tree, setTree] = useState(treeData);
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);
};
React.useEffect(() => {
const checked = [];
treeData.forEach((data) => {
data.children.forEach((item) => {
if (item.checked) {
checked.push(item.key);
}
});
});
setCheckedKeys(checked);
}, []);
React.useEffect(() => {
if (searchValue) {
const filteredData = filteredTreeData(
treeData,
searchValue,
checkedKeys,
setExpandedKeys
);
setTree([...filteredData]);
} else {
setTree(treeData);
// setExpandedKeys([]);
}
}, [searchValue, checkedKeys]);
return (
<div>
<Search
style={{ marginBottom: 8 }}
placeholder="Search"
onChange={(e) => {
setSearchValue(e.target.value);
}}
/>
<Tree
checkable
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onCheck={onCheck}
checkedKeys={checkedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={tree}
/>
</div>
);
};
CodeSandBox Link
Edited Response to fix uncheck issue
If I understood the question correctly, Is the issue with the fact that previous checked items are getting cleared on search and selection of new one?
I think the solution would be to use 2 different separate trees one for filtered and the other for normal.
Did some code changes on top of the sandbox code shared.
I have added a new tree when searchedValue is present.
On checking/unchecking the new filtered tree, the actual entire tree's checked values get updated
When the searched value is empty it would show the actual entire tree
Created a filteredKeys list to solve uncheck issue. Now I am able to select and unselect.
If you play around and refactor a bit, you should be able to achieve what you want.
Adding the same code below.
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Tree, Input } from "antd";
const { Search } = Input;
const treeData = [
{
title: "AP Watchlists",
key: "AP Watchlists",
children: [
{ title: "Colo Open Data", key: "Colo Open Data", checked: true },
{
title: "Department and trade",
key: "Department and trade",
checked: true
},
{
title: "North List",
key: "North List",
checked: true
},
{ title: "People's Daily", key: "People's Daily", checked: true }
]
},
{
title: "Af Watchlists",
key: "Af Watchlists",
children: [
{
title: "Service Wanted List",
key: "Service Wanted List",
checked: true
}
]
},
{
title: "EM Watchlists",
key: "EM Watchlists",
children: [
{
title: "National Financing",
key: "National Financing",
checked: true
},
{
title: "Arabia List",
key: "Arabia List",
checked: true
}
]
},
{
title: "Assets List",
key: "Assets List",
children: [
{
title: "National List",
key: "National List",
checked: true
}
]
},
{
title: "New Watchlists",
key: "New Watchlists",
children: [
{ title: "FATR", key: "FATR", checked: true },
{ title: "Internal", key: "Internal", checked: true },
{
title: "OC List (Covers 73 Lists)",
key: "OC List (Covers 73 Lists)",
checked: true
},
{ title: "UN", key: "UN", checked: true },
{
title: "Security List (Covers 18 Lists)",
key: "Security List (Covers 18 Lists)",
checked: true
}
]
}
];
const Demo = () => {
const hasSearchTerm = (n, searchTerm) =>
n.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1;
const filterData = (arr, searchTerm, keys) => {
const result = arr?.filter(
(n) =>
hasSearchTerm(n.title, searchTerm) ||
filterData(n.children, searchTerm, keys)?.length > 0
);
result &&
result.forEach((node) => {
if (keys.indexOf(node?.key) === -1) keys.push(node?.key);
});
return result;
};
function filteredTreeData(data, searchString, checkedKeys, setExpandedTree) {
let keysToExpand = [];
const keys = [];
const filteredData = searchString
? filterData(data, searchString, keys).map((n) => {
keysToExpand.push(n.key);
return {
...n,
children: filterData(n.children, searchString, keys)
};
})
: data;
setExpandedTree([...keysToExpand]);
setFilteredKeys(keys);
return filteredData;
}
const [expandedKeys, setExpandedKeys] = useState([]);
const [checkedKeys, setCheckedKeys] = useState([]);
const [filteredCheckedKeys, setFilteredCheckedKeys] = useState([]);
const [selectedKeys, setSelectedKeys] = useState([]);
const [autoExpandParent, setAutoExpandParent] = useState(true);
const [searchValue, setSearchValue] = useState("");
const [tree, setTree] = useState(treeData);
const [filteredTree, setFilteredTree] = useState([]);
const [filteredKeys, setFilteredKeys] = useState([]);
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);
// console.log("checkedKeys", checkedKeys);
setCheckedKeys(checkedKeysValue);
};
const onFilteredTreeCheck = (checkedKeysValue) => {
// console.log("onFilterCheck", checkedKeysValue);
// console.log("filteredcheckedKeys", filteredCheckedKeys);
setFilteredCheckedKeys(checkedKeysValue);
const baseTreeKeys = [...checkedKeys].filter(
(node) => filteredKeys.indexOf(node) === -1
);
console.log("baseTreeKeys", baseTreeKeys);
console.log("checkedKeysValue", checkedKeysValue);
setCheckedKeys([...checkedKeysValue, ...baseTreeKeys]);
};
const onSelect = (selectedKeysValue, info) => {
console.log("onSelect", info);
setSelectedKeys(selectedKeysValue);
};
// React.useEffect(() => {
// const checked = [];
// treeData.forEach((data) => {
// data.children.forEach((item) => {
// if (item.checked) {
// checked.push(item.key);
// }
// });
// });
// setCheckedKeys(checked);
// }, []);
React.useEffect(() => {
setFilteredKeys([]);
if (searchValue) {
const filteredData = filteredTreeData(
treeData,
searchValue,
checkedKeys,
setExpandedKeys
);
setFilteredTree([...filteredData]);
} else {
setTree(treeData);
// setExpandedKeys([]);
}
}, [searchValue, checkedKeys]);
console.log("filteredCHeckedValues", filteredCheckedKeys);
console.log("existing checked values", checkedKeys);
return (
<div>
<Search
style={{ marginBottom: 8 }}
placeholder="Search"
onChange={(e) => {
setSearchValue(e.target.value);
}}
/>
{searchValue ? (
<Tree
checkable
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onCheck={onFilteredTreeCheck}
checkedKeys={filteredCheckedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={filteredTree}
/>
) : (
<Tree
checkable
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
onCheck={onCheck}
checkedKeys={checkedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={tree}
/>
)}
</div>
);
};
ReactDOM.render(<Demo />, document.getElementById("container"));
Let me know if this solves your issue. I am able to select multiple values in subsequent searches without loosing the checked ones.
As mentioned in the API document, filterTreeNode will keep keys from the tree node, and will not hide it.
filterTreeNode
Defines a function to filter treeNodes. When the function returns true, the corresponding treeNode will be checked
If you want to hide tree node, you will have to manually filter it first before before passing it to Tree in loop function, something like:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Tree, Input } from "antd";
const gData = [
{
key: "1",
title: "title 1"
},
{
key: "2",
title: "title 2"
},
{
key: "3",
title: "title 3",
children: [
{
key: "4",
title: "title 4"
},
{
key: "5",
title: "title 5",
children: [
{
key: "6",
title: "title 6"
},
{
key: "7",
title: "title 7"
}
]
}
]
}
];
const { Search } = Input;
const dataList = [];
const generateList = (data) => {
for (let i = 0; i < data.length; i++) {
const node = data[i];
const { key } = node;
dataList.push({ key, title: key });
if (node.children) {
generateList(node.children);
}
}
};
generateList(gData);
const getParentKey = (key, tree) => {
let parentKey;
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.children) {
if (node.children.some((item) => item.key === key)) {
parentKey = node.key;
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children);
}
}
}
return parentKey;
};
const SearchTree = () => {
const [expandedKeys, setExpandedKeys] = useState([]);
const [autoExpandParent, setAutoExpandParent] = useState(true);
const [searchValue, setSearchValue] = useState("");
const [treeData, setTreeData] = useState(gData);
const onExpand = (expandedKeys) => {
setExpandedKeys(expandedKeys);
setAutoExpandParent(false);
};
const onChange = (e) => {
const value = e.target.value?.toLowerCase();
const expandedKeys = dataList
.map((item) => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.key, gData);
}
return null;
})
.filter((item, i, self) => item && self.indexOf(item) === i);
if (value) {
const hasSearchTerm = (n) => n.toLowerCase().indexOf(value) !== -1;
const filterData = (arr) =>
arr?.filter(
(n) => hasSearchTerm(n.title) || filterData(n.children)?.length > 0
);
const filteredData = filterData(gData).map((n) => {
return {
...n,
children: filterData(n.children)
};
});
setTreeData(filteredData);
setExpandedKeys(expandedKeys);
setSearchValue(value);
setAutoExpandParent(true);
} else {
setTreeData(gData);
setExpandedKeys([]);
setSearchValue("");
setAutoExpandParent(false);
}
};
const filterTreeNode = (node) => {
const title = node.title.props.children[2];
const result = title.indexOf(searchValue) !== -1 ? true : false;
console.log(searchValue);
console.log(result);
return result;
};
const loop = (data) =>
data.map((item) => {
const index = item.title.indexOf(searchValue);
const beforeStr = item.title.substr(0, index);
const afterStr = item.title.substr(index + searchValue.length);
const title =
index > -1 ? (
<span>
{beforeStr}
<span className="site-tree-search-value">{searchValue}</span>
{afterStr}
</span>
) : (
<span>{item.title}</span>
);
if (item.children) {
return { title, key: item.key, children: loop(item.children) };
}
return {
title,
key: item.key
};
});
return (
<div>
<Search
style={{ marginBottom: 8 }}
placeholder="Search"
onChange={onChange}
/>
<Tree
onExpand={onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
treeData={loop(treeData)}
filterTreeNode={filterTreeNode}
/>
</div>
);
};
ReactDOM.render(<SearchTree />, document.getElementById("container"));

extracting a function into standalone reactjs component throws Objects are not valid as a React child (found: [object Window])

When I render my the component below with useRowCellSettings as function in the component, it works with no error, how when extract useRowCellSettings into a standalone component it throws error.
import React from "react";
const MyDatatable = (props) => {
let columnHeaders = [
{title: "Id" , accessor: 'id' , index: 0},
{title: "Name" , accessor: 'name', width: "300px", index: 2}
]
let rowData = [
{id: 1, name: 'a', age: 29, qualification: 'B.com', rating: 3, profile: 'ps'},
{id: 2, name: 'b', age: 35, qualification: 'B.Sc', rating: 5, profile: 'h'}
]
const [headers, setHeaders] = React.useState(columnHeaders);
const [data, setData] = React.useState(rowData);
const renderContent = () => {
let contentView = data.map((row, rowIdx) => {
let id = row[keyField];
let tds = headers.map((header, index) => {
//grab the content of the column
let content = row[header.accessor];
let cell = header.custom_render_options;
content = useRowCellSettings(cell, content);
return (
<td key={index} data-id={id} data-row={rowIdx}>
{content}
</td>
);
});
return (
<tr key={rowIdx}>
{tds}
</tr>
);
//
}); //closes contentView variable
return contentView;
}
const useRowCellSettings = (cell, content) => {
if(cell) {
if (typeof(cell) === "object") {
//if (cell.type === 'image' && content) {
if (cell.type === 'image') {
//wrap the content with image tag & assign style from the cell
content = content ? <img style={cell.style} src={content} /> :
<><input type="file" id="img" name="img" /> </>
} //closes cell.type
} //close cell == object
else if (typeof(cell) === 'function') {
content = cell(content);
}
} //closes if cell
return content;
}
}
Extracting useRowCellSettings into a standalone component as shown below and then calling the new standalone component instead of useRowCellSettings function in the parent component result in the error:
Objects are not valid as a React child (found: [object Window]). If you meant to render a collection of children, use an array instead.
import React from "react";
const ImageType = (props) => {
if(props.cell) {
if (typeof(props.cell) === "object") {
if (props.cell.type === 'image') {
const content = props.content ? <img style={props.cell.style} src={content} /> : <input type="file" id="img" name="img" accept="image/*"/>
} //closes cel.type
} //close if cell == object
else if (typeof(props.cell) === 'function') {
const content = props.cell(content);
}
} //closes if cell
return content;
}
import React from 'react';
const ImageType = props => {
let content = null;
if (props.cell) {
if (typeof props.cell === 'object') {
if (props.cell.type === 'image') {
content = props.content ? (
<img style={props.cell.style} src={props.content} />
) : (
<input type='file' id='img' name='img' accept='image/*' />
);
}
} else if (typeof props.cell === 'function') {
content = props.cell(props.content);
}
}
return content;
};
You have mixed up the content variable.

How to add new Properties to File object in React with state value dynamically

I hope to be descriptive, Let's say I have a Files Object Array
JSONfiledata = [
{
lastModified:123444,
name: 'file1',
size: 0,
type: ""
},
{
lastModified:123445,
name: 'file2',
size: 0,
type: ""
},
{
lastModified:123446,
name: 'file3',
size: 0,
type: ""
}
]
And I have a this component that receives that data through props
import React, {useState} from 'react'
const component = ({files}) => {
const [inputValue, setInputValue] = useState('')
const eventHandler = (e) => setInputValue(e.target.value)
const addNewKey = files.map(fileObj => Object.defineProperty(fileObj, 'newKey', {
value: inputValue
}))
return (
{
files.map(fileData => (<div>
{fileData.name}
<input value={inputValue} onChange={setInputValue} />
</div>))
}
)
}
How can I mutate the current files object and add a 'newKey' on each one depending on the inputValue, but independently from each other.
I mean, at position 0 let's say I write on the input "this is the file number one"
at position 1 "this is the file number two" and so on ....
At the end, the expected output will be
[
{
lastModified:123444,
name: 'file1',
size: 0,
type: "",
newKey: "this is the file number one"
},
{
lastModified:123445,
name: 'file2',
size: 0,
type: "",
newKey: "this is the file number two"
},
{
lastModified:123446,
name: 'file3',
size: 0,
type: "" ,
newKey: "this is the file number three"
}
]
I build a solution:
Build another component to manage every file individualy.
Like this:
import React, { useState } from 'react';
import { Map } from './Map';
export const MapList = ({ files }) => {
const [filesState, setFilesState] = useState([...files]);
const handleChange = nObject => {
/**You can compare with a unique id, preferably */
setFilesState(filesState => filesState.map(file => (file.name === nObject.name ? nObject : file)));
};
return (
<div>
{filesState.map(file => (
// If you have an ID you can send in this plance, to be more simple find the object in the handle function
<Map handleChange={handleChange} file={file} />
))}
<h2>Files Change</h2>
{filesState.map(file => (
<div>
<p>
{file.name} {file.newKey && file.newKey}
</p>
</div>
))}
</div>
);
};
In this wrapper component, you will update the entry array, with the handleChange function.
After you can build a component to manage your new key, for example:
import React, { useState } from 'react';
export const Map = ({ file, handleChange }) => {
const [input, setInput] = useState('');
const handleChangeKey = e => {
const { name, value } = e.target;
const nFile = { ...file, [name]: value };
setInput(value);
handleChange(nFile);
};
return (
<div>
<div>
<label htmlFor={file.name}>
<small>Input for: {file.name}</small>{' '}
</label>
<input id={file.name} name='newKey' value={input} onChange={handleChangeKey} type='text' />
</div>
</div>
);
};
It works for me, i think is a solution maybe not the best, but is a simple solutions.
const JSONfiledata = [
{
lastModified:123444,
name: 'file1',
size: 0,
type: ""
},
{
lastModified:123445,
name: 'file2',
size: 0,
type: ""
},
{
lastModified:123446,
name: 'file3',
size: 0,
type: ""
}
];
const fileNameToUpdate = 'file2';
const newKey = "file2Key";
const newArray = JSONfiledata.map((item) => {
if (item.name === fileNameToUpdate) {
return {...item, newKey: newKey };
} else {
return item;
}
});
console.log(`newArray==`, newArray);

How can i do a list of objects in javascript?

I am using react, and i need to add files in a list.
this.state = {
some: {
names: [],
keys: 0
}
file: {
images: []
}
}
newSome = () => {
const some = {
...this.state.some,
['name'] = 'inputed name',
[keys] = this.state.some.keys++
}
handleChange = (field,key) => event => {
const file = {...this.state.file}
file['images'].push({[key] : event.target.files[event.target.files.length-1]})
this.setState({file})
}
render(){
const {key} = this.state.some
return (
<input type='file' onChange={this.handleChange('images', key)}/>
)
}
i have a dictionary that has as "name with image" and "name without image". in images, i have the images of names. For example: name['maria', 'joao', renato], and joao doesn't have image... so in images i have images[{0: file0},{2: file1}]. When i load a image, in first operation, it works, but in second doesn't work, and appear the error TypeError: file.images.push is not a function. What i have to do?
state = {
some: {
names: [],
key: ""
},
file: {
images: []
}
};
handleChange = (field, key) => event => {
const { files } = event.target;
const file = {
images: [...this.state.file.images, { [key]: files[files.length - 1] }]
};
this.setState({ file });
};
render() {
const { key } = this.state.some;
return <input type="file" onChange={this.handleChange("images", key)} />;
}

Categories

Resources