Try2prog
Try2prog

Reputation: 191

How to perform correct useState within these code?

I have an issue with the render, so I've been told to set the table I use as a state so the data could update correctly.

The table I'm using:

<ScrollView horizontal={true} style={{ marginTop: 20 }}>
  <View>
    <Table borderStyle={{ borderWidth: 1, borderColor: '#C1C0B9' }}>
      <Row
        data={this.state.tableHead}
        widthArr={this.state.widthArr}
        style={styles.header}
        textStyle={styles.text}
      />
    </Table>
    <ScrollView style={styles.dataWrapper}>
      <Table borderStyle={{ borderWidth: 1, borderColor: '#C1C0B9' }}>
        {this.state.tableData.map((rowData, index) => (
          <Row
            key={index}
            data={rowData}
            widthArr={this.state.widthArr}
            style={[styles.row, index % 2 && { backgroundColor: '#F7F6E7' }]}
            textStyle={styles.text}
          />
        ))
        //this.state.myState
        }
      </Table>
    </ScrollView>
  </View>
</ScrollView>

It's working under render() and I try to make a setState onPress option to activate it, I did something like:

updateState = () =>
  this.setState({
    myState: this.state.tableData.map((rowData, index) => (
      <Row
        key={index}
        data={rowData}
        widthArr={this.state.widthArr}
        style={[styles.row, index % 2 && { backgroundColor: '#F7F6E7' }]}
        textStyle={styles.text}
      />
    )),
  })

But can't get it to work.

Upvotes: 0

Views: 45

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

Add a toggle state. This state will change on every onPress event.

(for the sample below, I'm using onClick)

const {useState} = React;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      toggle: false,
    };
    this.data = [1, 2, 3, 4];
  }

  render() {
    return (
      <div>
        <button onClick = {
          () => this.setState({ toggle: !this.state.toggle })
        }>
          {this.state.toggle ? 'hide' : 'show'}
        </button>
        {this.state.toggle ? this.data.map(d => (
          <div>{d}</div>
        )) : null}
      </div>
    );
  }
}

ReactDOM.render(
  <App /> ,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 1

Related Questions