I am trying to display a table with data coming from an API. Below is my Table.js component:
import React from "react";
import { useTable } from "react-table";
export default function Table({ columns, data }) {
// Use the useTable Hook to send the columns and data to build the table
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable({
columns,
data
});
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
}
My component Screen.js is as below:
import React, { useEffect, useState, useMemo } from 'react';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, View } from 'react-native';
import { getProjects } from '../utils/data';
import Table from "../components/Table";
const ProjectsListScreen = () => {
const [projects, setProjects] = useState([]);
useEffect(() => {
(async () => {
try {
const projectsData = await getProjects();
setProjects(projectsData.objects);
console.log('Fetched projects:', projectsData.objects);
} catch (error) {
console.log('Error when fetching projects:', error);
}
})();
}, []);
const columns = useMemo(
() => [
{
Header: "Projects",
// First group columns
columns: [
{
Header: 'Name',
accessor: 'project.name',
},
{
Header: 'Type',
accessor: 'project.type',
}
]
},
{
Header: "Details",
// Second group columns
columns: [
{
Header: 'Systems',
accessor: 'project.numberOfSystems',
},
{
Header: 'Starting date',
accessor: 'project.start',
},
{
Header: 'Customer',
accessor: 'project.customer',
}
]
}
],
[]
);
return (
<View style={styles.container}>
<Table columns={columns} data={projects}/>
<StatusBar style="auto" backgroundColor='green'/>
</View>
);
}
export default ProjectsListScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
I have tested separately the fetching function successfully.
If I try the app on Expo, I have the following error:
Error: Text strings must be rendered within a <Text> component.
This error is located at:
in th (at Table.js:27)
in tr (at Table.js:25)
in thead (at Table.js:23)
in table (at Table.js:22)
If I log all the column.render(“Header”), they display correctly in the console under the form of strings.