I am currently using the method "table" which is inside a class-component to render several table items (table rows).
The function uses the component "Row" for the table row.
It seems a bit verbose and I wonder if there is the chance to pass properties to the child in a more compact way ?
//table is a method inside a class
public table(data: any[] | ""){
return (
<table>
{data !== "" && data.map((item)=>{
return (<Row
name={item.name}
x={item.meta.xAxisUnits}
y={item.meta.yAxisUnits}
memo={item.meta.memo} />
)}
</table>
)
}
}
function Row(props:any){
return (<tr>
<td>props.name</td>
<td>props.x</td>
<td>props.y</td>
<td>props.memo</td>
</tr>
)}
```
CodePudding user response:
You could pass item and let Row figure it out.
<Row item={item} />
And if you don't want that logic in the Row component you could establish a list of columns that Row just iterates:
const columns = [
item => item.name,
item => item.meta.xAxisUnits,
item => item.meta.yAxisUnits,
item => item.meta.memo,
];
function Row({item}) {
return (
<tr>
{ columns.map((c, i) => (
<td key={i}>{c(item)}</td>
))}
</tr>
)
}
CodePudding user response:
You could compose your components, like follow:
const Row = (props:any) => (
<tr>
<td>props.name</td>
<td>props.x</td>
<td>props.y</td>
<td>props.memo</td>
</tr>
)
const Table = ({children}) => (
<table>
{children}
</table>
)
Table.Row = Row;
// and then use it like this:
<Table>
{item.map((i) => <Table.Row {...i} />)}
</Table>