Getting the extension of file (array of objects)
Hi, in this React code I have an array of objects with property name that is a string that simulate the name of the file with different extensions.
We are going to get the extension of the file names with Javascript:
Code
// Array of objects
const documentsFiles = [
{
name: 'myFirstDocument.doc'
},
{
name: 'myFirstExcel.xml'
},
{
name: 'MyFirstPDF.pdf'
},
{
name: 'MySe.cond.Doc.u.m.ent.doc'
},
{
name: 'mysecondexcel..xml'
},
{
name: '.YSECONDPDF.pdf'
}
];
// Method for render files
const renderFiles = (data: any): ReactElement => {
return data.map((document: any, i: any) => {
// This JS code get the file extension
const extension =
document.name.substr(document.name.lastIndexOf('.') + 1)
// In that we can assign a Icon depend of the extension
return (
<section key={`file-${i}`}>
{extension === 'doc' && <i className="fas fa-file-word" style=
{{ color: '#0061a7' }} />}
{extension === 'pdf' && <i className="fas fa-file-pdf" style=
{{ color: '#f30000' }} />}
{extension === 'xml' && <i className="fas fa-file-excel"
style={{ color: '#3b6e22' }} />}
<span>{document.name}</span>
</section>
)
})
}
Result:
By Cristina Rojas.