Search code examples
javascriptreactjsecmascript-6react-reduxsemantic-ui-react

How to update my react state with active tab menu name so it can pass on to the endpoint call?


I am working on a react app where I need to display data for multiple pages based on the dynamic parameter value that I pass to the backend api call. I am using the Tab component from semantic-ui-react and I can't figure out how I can pass the name of the active menu/page to my state so that it can pass on to the api method as a parameter. Depending on the page name, the backend returns data differently for each page.

I've put together my code in sandbox if someone can please help me out

https://codesandbox.io/s/eager-leakey-0emhz?file=/src/App.js

import React from "react";
import { Tab } from "semantic-ui-react";
import "./styles.css";
import { connect } from "react-redux";
import ApiActions from "./actions/";
import { API_PAGE_GET_SUCCESS } from "./actions/types";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      activeIndex: 0,
      nav_menu: [
        { menuItem: "Dashboard", render: () => "Dashboard page" },
        { menuItem: "Profile", render: () => "Profile page" },
        { menuItem: "Contact", render: () => "Contact page" }
      ]
    };
  }

  componentDidMount() {
    this.getPage();
  }

  getPage() {
    const { getPageData } = this.props;

    getPageData("dashboardPage").then((response) => {
      if (response.type == API_PAGE_GET_SUCCESS) {
        this.setState({
          data: response.payload
        });
      }
    });
  }

  handleTabChange = (e, { activeIndex }) => this.setState({ activeIndex });

  render() {
    const { activeIndex, nav_menu } = this.state;
    return (
      <>
        <Tab
          id="sidebar"
          menu={{
            fluid: false,
            vertical: true,
            secondary: true,
            pointing: true
          }}
          menuPosition="left"
          panes={nav_menu}
          activeIndex={activeIndex}
          onTabChange={this.handleTabChange}
        />
      </>
    );
  }
}

export const mapDispatchToProps = (dispatch) => ({
  getPageData: (page) => {
    const action = ApiActions.common.getPageData(page);
    const response = dispatch(action);
    return response;
  }
});

export default connect(null, mapDispatchToProps)(App);

Solution

  • you can grab the name from the state :

    getPage() {
      const { getPageData } = this.props;
      const { activeIndex, nav_menu} = this.state;
    
      const currentPage = nav_menu[activeIndex].menuItem;
    
      getPageData(currentPage || "dashboardPage").then((response) => {
        if (response.type == API_PAGE_GET_SUCCESS) {
          this.setState({
            data: response.payload
          });
        }
      });
    }