Home > Software design >  how to add checkbox in table view react-native
how to add checkbox in table view react-native

Time:08-18

I'm using react native expo. and trying to add table with checkbox functionality on check uncheck getting rowid and condition true or false and I want to add checkbox in react-native-table-component . I'm using below react native package for table . add checkbox but doesn't work.

I'm trying last one hour but doesn't success kindly help me below mentioned code.

I'm using expo-checkbox package for checkbox

enter image description here

CodePudding user response:

You are mixing react class components and react functional components. You cannot call hooks inside the render function of your class component. Thus, the statement

render() {
    ...
    
    const [agree, setAgree] = useState(false);
    
    ...
}

is the issue here. Since you want a checkbox in each cell of a particular column you will need a state array and create a bijection between table indices and array elements of that state. You can keep this state in the class component as usual.

Judging from the provided code, it seems that you want to add a checkbox in the third column in every row. Furthermore, I have removed the TouchableOpacity. I guess that this was copied from the documentation.

Here is one possible solution.

export default class ExampleFour extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableHead: ['RollNo', 'Name', 'Father Name', 'Action'],
      tableData: [
        ['1', '2', '3', '4'],
        ['a', 'b', 'c', 'd'],
        ['1', '2', '3', '4'],
        ['a', 'b', 'c', 'd']
      ],
      checks: [false, false, false, false],
    }
  }

  render() {
    const state = this.state;
    const element = (data, index) => (
        <CheckBox
          value={state.checks[index]}
          onValueChange={() => this.setState(prev => ({...prev, checks: prev.checks.map((value,i) => i === index ? !value : value)}))}
          color={state.checks[index] ? "#4630EB" : undefined}
        />
    );

    return (
      <View style={styles.container}>
          
        <Table borderStyle={{borderColor: 'transparent'}}>
          <Row data={state.tableHead} style={styles.head} textStyle={styles.text}/>
          {
            state.tableData.map((rowData, index) => (
              <TableWrapper key={index} style={styles.row}>
                {
                  rowData.map((cellData, cellIndex) => (
                    <Cell key={cellIndex} data={cellIndex === 3 ? element(cellData, index - 1) : cellData} textStyle={styles.text}/>
                  ))
                }
              </TableWrapper>
            ))
          }
        </Table>
      </View>
    )
  }
}
  • Related