utilizing the value within the useState function, however, when attempting to utilize it within this.state, the tab switching feature fails

class SimpleTabs extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedButton: false,
      value: 0
    };

    // const classes = useStyles();
    // const [value, setValue] = React.useState(0);
  }

  handleChange = (event, newValue) => {
    // const classes = useStyles();
    console.log("handleChange--->");
    const [value, setValue] = React.useState(0);
    setValue(newValue);
  };

  render() {
    //const classes = useStyles();
    const { classes } = this.props;
    //  const [value, setValue] = React.useState(0);

    return (
      <div className={classes.root}>
        <AppBar position="static">
          <Tabs value={this.state.value} onChange={this.handleChange}>
            <Tab label="Item One" />
            <Tab label="Item Two" />
            <Tab label="Item Three" />
          </Tabs>
        </AppBar>
        {this.state.value === 0 && <TabContainer>Item One</TabContainer>}
        {this.state.value === 1 && <TabContainer>Item Two</TabContainer>}
        {this.state.value === 2 && <TabContainer>Item Three</TabContainer>}
      </div>
    );
  }
}

export default withStyles(styles)(SimpleTabs);

Answer №1

If you're working with class components, remember that hooks cannot be used inside them. Hooks should only be used in functional components. Instead, rely on this.state and this.setState for managing state.

  handleChange = (event, newValue) => {
    this.setState({
      value: newValue;
    });
  };

Alternatively, consider refactoring your component into a functional one. Here's a simplified version without the selected button:

const SimpleTabs = (props) => {
  const { classes } = props;
  const [value, setValue] = useState(0);

  const handleChange = useCallback((event, newValue) => {
    setValue(newValue);
  }, [])

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Tabs value={value} onChange={handleChange}>
          <Tab label="Item One" />
          <Tab label="Item Two" />
          <Tab label="Item Three" />
        </Tabs>
      </AppBar>
      {value === 0 && <TabContainer>Item One</TabContainer>}
      {value === 1 && <TabContainer>Item Two</TabContainer>}
      {value === 2 && <TabContainer>Item Three</TabContainer>}
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dropdown menu using React库

The API response I received looks like this:- [ { "Product.Name": "Data Migration - Test1", "Product.Id": "8ad0", "Product.Hello__c": { "Value": "First ...

Can you explain the meaning of this compound CSS selector?

.btnBlue.btnLtBlue Is this referring to an element that has both the classes btnBlue and btnLtBlue applied? ...

Creating a personalized cover for devextreme column in datagrid: A Step-by-Step Guide

I have encountered an issue with wrapping a Column inside my DataGrid. My goal is to create a customized component that generates a Column with the correct formatting. For instance, I want to develop a ColumnDate component that includes specific date forma ...

What is the best way to close an ajax page within the main page using a button?

I am dealing with a situation where I have 2 pages. The first page contains a div called 'ajaxicall', which loads another page inside it. The challenge I am facing is figuring out how to close the second page when I click on the "close" button w ...

Using JavaScript, you can add an article and section to your webpage

Currently, I am utilizing AJAX to showcase posts. My objective is to extract each property from a JSON object that is returned and generate an <article> for the title followed by a subsequent <section> for the content. While I can successfully ...

Retrieve a specific object from a JSON array nested within an array of objects, by utilizing a PHP script

There are two JSON files that contain JSON objects, with one of the files containing an array of objects within another array of objects. The first file is orders.json: { "orders": [ { "address": null, ...

What is the best way to personalize material-ui V1 components throughout my application by establishing a theme?

When working with material-ui v0, I discovered that it was easy to customize themes by adding properties to themeOptions for each component. This file: https://github.com/mui-org/material-ui/blob/master/src/styles/getMuiTheme.js (from the master branch), a ...

Converting from Async.js parallel to Bluebird: A Step-by-Step Guide

Utilizing async.js allows me to define promises with handlers, providing polymorphism and separating results. Can this be achieved in bluebird as well? async.parallel({ cityPromises: (cb)=>{ City.find({ ...

Download function in Express.JS failing to retrieve file

I have been working on a Node.JS server using Express to generate and download PDFs based on user input. Previously, I used the <form action=""> method to call my API, but switched to Axios due to Netlify not supporting NuxtAPI. The program ...

Issues arise when trying to integrate external JavaScript files into a Vue application

I am facing an issue with including external JS files in my HTML document. The website requires these files to function properly. What I have attempted: In the main.js file, I tried adding these imports: import '../../assets/js/jquery-3.5.1.min&apos ...

Guide on aligning a child div directly beneath its parent without specifying the parent's height

I want to position a div beneath its parent in a way that mimics a menu opening below it. Currently, I attempted using right and top, but the child div ends up overlapping the parent. If the parent had a defined height (rather than top: 0 as shown below), ...

Ways to align elements vertically in a container without using flexbox?

I am working with a ul element that has a height of 270px and contains 10 li elements. My goal is to have all the li elements vertically justified, meaning the top and bottom li elements should touch the container's top and bottom respectively, while ...

What is the best way to strip the text from a link that encompasses both text and an image using jquery?

I have a website with a list of items. Each item in the list has a link that includes both text and an image. Here is an example of the HTML structure: <li class="li-one" style=""> <a href="#" onclick="return ...

PHP - Extract Information from Table Upon Form Submission without User Input

I'm facing a challenge with my web form that includes a table allowing users to delete rows before submitting. Although there are no input fields in the table, I need to capture the data from these rows when the form is submitted. The issue is that th ...

Transferring data between browser tabs in Next.js and automatically populating a formik form

I have a form on my page with a single input field for a name. When this form is submitted, I want to open a new tab in the browser that displays a form with more inputs such as name, address, and age. How can I pre-fill the name in the new tab? I was thi ...

Tally up identical words without considering differences in capitalization or extra spaces

Let's take an example with different variations of the word "themselves" like "themselves", "Themselves", or " THEMSelveS " (notice the leading and trailing spaces), all should be considered as one count for themselves: 3 ...

The property was computed but cannot be set - specifically for a toggle component

I am currently working on developing a switch toggle component in Vue that includes a v-model and @updated. However, I am encountering difficulties when trying to update the model once the user toggles the switch. Initially, I faced an issue regarding muta ...

Is there a way to shift a background image pattern?

After searching extensively, I came up empty-handed and am seeking guidance on how to achieve a specific effect. Specifically, I am in need of a JavaScript or jQuery script that can smoothly shift a background image to the right within a designated div con ...

Searching with Neo4j, Java and the Angular library for accurate

When my web application is opened, it displays a form where users can input a list of comma-separated usernames. The application then queries the neo4j database to fetch information for each username. I am interested in implementing autocomplete functiona ...

Learn how to create a disappearing dropdown menu in React that closes automatically when you select a specific category

I'm encountering an issue with a dropdown menu that remains visible on the screen even after selecting a specific category. The selected category is displayed in a box upon selection, but the dropdown menu doesn't disappear as intended. I am look ...