1

I am trying to find a way to run a component (FetchData), which is a pop up grid and an API pull, through a Button, so when I click the button the component renders. I am not sure what to do here (new to JS). I am using the Material UI drawer. Is there something that I am missing here?

class MiniDrawer extends React.Component {
  state = {
    open: false,
  };

  handleDrawerOpen = () => {
    this.setState({ open: true });
  };

  handleDrawerClose = () => {
    this.setState({ open: false });
  };


  render() {
    const { classes, theme } = this.props;

    return (
      //main part of where help is needed
        <main className={classes.content}>
          <div className={classes.toolbar} />

          <Button onClick={this.handleClick}>{'Get Devices'}</Button>
          <FetchData />

        </main>
      </div>
    );
  }
}

MiniDrawer.propTypes = {
  classes: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
};

export default withStyles(styles, { withTheme: true })(MiniDrawer);
Tjm8679
  • 15
  • 6
  • 1
    Where is your button onClick event handler and do you want to call FetchData only when the button is clicked is that your query? – Hemadri Dasari Aug 25 '18 at 04:52
  • Possible duplicate of [Show or hide element in React](https://stackoverflow.com/questions/24502898/show-or-hide-element-in-react) – jmargolisvt Aug 25 '18 at 04:54

1 Answers1

0

From your question what I understand is that you want to call FetchData only when the button is clicked. If so then you need to have a boolean in state like below. When the button is clicked then make that boolean to true using setState and call FetchData component only when the boolean is true. Now, you also need to make it false in order for its to work again when the button is clicked second time. So you can do that in drawer close event handler.

class MiniDrawer extends React.Component {
  state = {
    open: false,
    callFetchData: false
  };

  handleDrawerOpen = () => {
    this.setState({ open: true });
  };

  handleDrawerClose = () => {
    this.setState({ open: false, callFetchData: false });
  };

  handleClick = () => {
    this.setState({
      callFetchData: true
    });
  }
  render() {
    const { classes, theme } = this.props;
    const { callFetchData } = this.state;
    return (
      //main part of where help is needed
        <main className={classes.content}>
          <div className={classes.toolbar} />

          <Button onClick={this.handleClick}>{'Get Devices'}</Button>
          {callFetchData && <FetchData />}

        </main>
      </div>
    );
  }
}

MiniDrawer.propTypes = {
  classes: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
};

export default withStyles(styles, { withTheme: true })(MiniDrawer);
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162