Reputation: 1010
I am using react with typescript and I can't map my object. I am pretty confused so as a last result here I am asking how to fix this
Object.keys and the below in my code don't print any console log
import React, { Component, useEffect } from 'react'
export interface FileInputControlIProps {
id?: string,
label?: string,
name?: string,
value?: any,
type?: string,
handleChange: Function,
attachments?: any,
}
export const FileInputControl = (props: FileInputControlIProps) => {
const attachmentDetails = (files) => {
console.log(typeof(files))
for (const [key, value] of Object.entries(files)) {
console.log(`${key}: ${value}`);
}
}
const { handleChange, type, name, id, attachments, label} = props;
return (
<div className="form-group">
<div className="label-container">
<label htmlFor="Attachments" className="form-label">{label}</label>
</div>
<div className="control-container">
<input type={type} name={name} id={id} multiple={true} onChange={(e) => handleChange(e)} />
<ul className="attachment-file">
{console.log(attachments)}
{console.log(attachments === undefined)}
{attachments &&
attachmentDetails(attachments)
}
</ul>
</div>
</div>
)
}
Upvotes: 0
Views: 1502
Reputation: 1799
Modify according to your needs, but the main issue is that you first have to iterate over the array of files and then within each file, you should get the key values.
import React, { Component, useEffect } from 'react'
export interface FileInputControlIProps {
id?: string,
label?: string,
name?: string,
value?: any,
type?: string,
handleChange: Function,
attachments?: any,
}
export const FileInputControl = (props: FileInputControlIProps) => {
const attachmentDetails = (files) => {
files.forEach(file => {
Object.entries(file).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
})
})
}
const { handleChange, type, name, id, attachments, label} = props;
return (
<div className="form-group">
<div className="label-container">
<label htmlFor="Attachments" className="form-label">{label}</label>
</div>
<div className="control-container">
<input type={type} name={name} id={id} multiple={true} onChange={(e) => handleChange(e)} />
<ul className="attachment-file">
{console.log(attachments)}
{console.log(attachments === undefined)}
{attachments &&
attachmentDetails(attachments)
}
</ul>
</div>
</div>
)
}
Regarding the typeof
In the following example doing a console.log
of an array gives you object
, for this I suggest the second approach (Array.isArray
)
const array = [1, 2, 3];
console.log(typeof array);
console.log(Array.isArray(array));
Upvotes: 1