Home:ALL Converter>I need help in converting react class component to react hooks

I need help in converting react class component to react hooks

Ask Time:2019-04-11T15:17:54         Author:Tahir Iqbal

Json Formatter

I am beginner in react hooks, i am also using graphql in my project. Someone can help in converting a component to react hooks.

class Detail extends Component {
  static propTypes = {
    classes: PropTypes.shape(commonStyles).isRequired,
    siteId: PropTypes.string
  };
  state = {
    showDialog: false
  };
  handleRowHistory = () => {
    this.setState({ showDialog: true });
  };
  render() {
    const { showDialog } = this.state;
    const { data, classes, siteId } = this.props;
    if (data.error) {
      return <CardErrorIndicator apolloData={data} />;
    } else if (data.loading) {
      return <CardLoadingIndicator />;
    }
    const { sites } = data;
    const { controller } = _.first(sites);

    return (
      <div
        className={classNames(
          classes.overall,
          classes.basePadding,
          "site-assets-detail-page"
        )}
      >
        <SiteRowController
          controller={controller}
          onRowHistoryClick={this.handleRowHistory}
        />
        {showDialog && (
          <RowHistoryDialog
            open={showDialog}
            siteId={siteId}
            onClose={() => this.setState({ showDialog: false })}
          />
        )}
      </div>
    );
  }
}

const DetailWithData = compose(
  graphql(SITE_ASSETS_DETAIL_QUERY, {
    options: props => ({
      variables: {
        siteId: props.siteId
      },
      pollInterval: 5000
    })
  })
)(Detail);

export default withStyles(commonStyles)(DetailWithData);

I understand that React-Hooks is alternative to React Class style. The question is if I can refactor and add React hooks into this.

Thanks

Author:Tahir Iqbal,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55626725/i-need-help-in-converting-react-class-component-to-react-hooks
Brian Le :

The only 2 hooks you need to know in this case are useState() and useCallback() (optionally). For the prop types you can declare them separately. So combine all these your code should look roughly like this:\n\nconst Detail = ({ data, classes, siteId }) => {\n const [showDialog, setShowDialog] = useState(false);\n const handleRowHistory = () => {\n setShowDialog(true);\n }; // You might need to use useCallback to stop new functions from being created\n\n if (data.error) {\n return <ErrorComponent />;\n }\n if (data.loading) {\n return <LoadingComponent />;\n }\n\n return <YourComponent />;\n};\n\nDetails.propTypes = {\n // Declare your prop types here\n};\n\n\nYou might want to check out React docs for hooks for further reference.",
2019-04-11T07:27:45
yy