What I want is setting all the cells width in a column as widest cell in the column.
For example I have a column and there are cells in that column. Cells have widths by their contents like; 30px, 40px, 30px, 50px, 25px
. And I want all the columns width as 50px
.
There is no display: table
in React Native. There are just flex
and none
. HTML Tables do this process automatically. I tried to set widths after onLayout event is invoked. But this approach seems slow to me. I am trying to find another solution.
How to achieve this in React Native?
You can usually handle this using FlatList
. The numColumns
prop sets the number of columns. Then, use width
and maxWidth
for the item in the renderItem
function to set a maximum width of the table cell.
Here is a minimal example simulating the one in your question. The background colour for each cell is green and the color for the content is either red or yellow. Hence, we can see how each cell has the same width, while the content has different widths.
const data = [
{
id: 1,
width: 30,
color: "red"
},
{
id: 2,
width: 40,
color: "yellow"
},
{
id: 3,
width: 30,
color: "red"
},
{
id: 4,
width: 50,
color: "yellow"
},
{
id: 5,
width: 35,
color: "red"
}
]
export default function App() {
return (
<View style={{margin: 40}}>
<FlatList
data={data}
numColumns={3}
keyExtractor={item => item.toString()}
renderItem={({item}) => {
return <View style={{ maxWidth: 50, width: 50, backgroundColor: "green"}}>
<View style={{width: item.width, backgroundColor: item.color, heigh: 40}}>
<Text>hello</Text>
</View>
</View>
}}
/>
</View>
);
}
The above yields to the following output.