Created
October 13, 2020 22:06
-
-
Save brunopk/0001e44fa6375bb27a704abedcd1e304 to your computer and use it in GitHub Desktop.
React Native component to show an editable table created with react-native-table-component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import styled from 'styled-components/native'; | |
import {StyleSheet, TouchableOpacity, View} from 'react-native'; | |
import {Icon} from 'react-native-elements'; | |
import {Colors} from 'react-native/Libraries/NewAppScreen'; | |
import {Color} from '../styles'; | |
import {Table, Cell, Row, TableWrapper} from 'react-native-table-component'; | |
const HEIGHT_HEADER_AND_BTN = 30; | |
const styles = StyleSheet.create({ | |
borderTable: {borderWidth: 2, borderColor: Color.blue}, | |
headTable: { | |
height: HEIGHT_HEADER_AND_BTN, | |
backgroundColor: Color.blue, | |
}, | |
headText: { | |
color: Colors.white, | |
paddingLeft: 12, | |
}, | |
cellText: { | |
margin: 5, | |
}, | |
rowTable: { | |
flexDirection: 'row', | |
backgroundColor: '#fff', | |
}, | |
cellDelete: { | |
textAlign: 'center', | |
backgroundColor: Color.red, | |
}, | |
}); | |
function IconButton({iconName, backgroundColor}) { | |
const StyledView = styled.View` | |
background-color: ${backgroundColor}; | |
height: ${HEIGHT_HEADER_AND_BTN + 'px'}; | |
justify-content: center; | |
`; | |
return ( | |
<TouchableOpacity onPress={() => console.log()}> | |
<StyledView> | |
<Icon name={iconName} size={15} color="white" type="font-awesome" /> | |
</StyledView> | |
</TouchableOpacity> | |
); | |
} | |
function StyledTable({table, editable = true}) { | |
const renderRow = (rowData, rowIndex) => { | |
let cells = rowData.map((cellData, cellIndex) => ( | |
<Cell key={cellIndex} data={cellData} textStyle={styles.cellText} /> | |
)); | |
if (editable) { | |
cells.push( | |
<Cell | |
key={rowData.length + 1} | |
data={<IconButton iconName="remove" backgroundColor={Color.red} />} | |
width={30} | |
textStyle={styles.cellDelete} | |
/>, | |
); | |
} | |
return ( | |
<TableWrapper key={rowIndex} style={styles.rowTable}> | |
{cells} | |
</TableWrapper> | |
); | |
}; | |
return ( | |
<Table borderStyle={styles.borderTable}> | |
<Row | |
data={table.head} | |
style={styles.headTable} | |
textStyle={styles.headText} | |
/> | |
{table.data.map((rowData, rowIndex) => renderRow(rowData, rowIndex))} | |
{editable ? ( | |
<Cell | |
key={table.data.length + 1} | |
data={<IconButton iconName="plus" backgroundColor={Color.blue} />} | |
/> | |
) : ( | |
<></> | |
)} | |
</Table> | |
); | |
} | |
export {StyledTable}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment