Having trouble with the state in ReactJS Material UI?

I'm facing an issue where I want the state of my component to change when I click on a MenuItem. Here's how I'm trying to achieve it:

export default class MenuAlumno extends React.Component {
constructor() {
    super();
    this.state = {
        drawerOpen:false,
        currentPage: 'Inicio'
    }
};

currentPages = (currentPage) => {
    this.setState({ 
        currentPage: currentPage
    });
}

render() {
    return (
        <div>
            <Drawer 
                docked = {false}
                width = {200}
                open = {this.state.drawerOpen}
                onRequestChange = {(drawerOpen) => this.setState({drawerOpen})}
            >
                <MenuItem primaryText = "Inicio" onTouchTap = {this.currentPages('Inicio')} containerElement = {<Link to="/administrador/inicio"/>}/>
                <MenuItem primaryText = "Nueva Incidencia" onTouchTap = {this.currentPages('Nueva Incidencia')} containerElement = {<Link to="/administrador/nueva_incidencia"/>}/>
                <MenuItem primaryText = "Incidencias Recibidas" onTouchTap = {this.currentPages('Incidencias Recibidas')} containerElement = {<Link to="/administrador/incidencias_recibidas"/>}/>
                <MenuItem primaryText = "Informes" onTouchTap = {this.currentPages('Informes')} containerElement = {<Link to="/administrador/informes"/>}/>
            </Drawer>
        </div>
    );
}

However, I'm encountering the following error:

Warning: setState(...): Cannot update during an existing state transition (such as within 'render' or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to 'componentWillMount'.

Any suggestions on how to resolve this issue? Appreciate any help.

EDIT: ----

If I do this: (adding ()=> begin the call function)

<MenuItem primaryText = "Inicio" onTouchTap = {() => this.currentPages('Inicio')} containerElement = {<Link to="/administrador/inicio"/>}/>
                <MenuItem primaryText = "Nueva Incidencia" onTouchTap = {() => this.currentPages('Nueva Incidencia')} containerElement = {<Link to="/administrador/nueva_incidencia"/>}/>
                <MenuItem primaryText = "Incidencias Recibidas" onTouchTap = {() => this.currentPages('Incidencias Recibidas')} containerElement = {<Link to="/administrador/incidencias_recibidas"/>}/>
                <MenuItem primaryText = "Informes" onTouchTap = {() => this.currentPages('Informes')} containerElement = {<Link to="/administrador/informes"/>}/>

Although no errors occur, the functionality does not work as expected. The state is not updated when clicking on a MenuItem. Instead, it remains at 'Inicio', and only changes after clicking twice on the same option. Could this be related to Linking to other routes causing re-rendering of the menu component? Any solutions?

Thank you for your assistance.

Answer №1

To resolve the issue, I included a property in my MenuAlumno component when calling it with the desired current page name. This method proved effective. I am open to exploring alternative solutions if any are available. Farewell.

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

Is it possible to align an entire column to the right in the Material UI Data Grid?

I'm currently exploring Material UI and grappling with a specific challenge. Is there a method within Material UI to create a Data Grid with two columns, one left-aligned and the other right-aligned? I've managed to align the headers as desired, ...

`Visualizing Material UI Checkbox Alignment`

Is there a way to vertically align my checkbox with the Calendar element instead of it always being positioned to the right due to padding issues? The invites are not aligned properly as well. <Grid item xs={12} > <Typography noWrap className= ...

Choosing an HTML element within a useEffect Hook

Having an issue with selecting an element inside another element in the DOM that was selected using the useRef hook. const editorRef = useRef(null); Trying to access the child element on the editorRef within a useEffect hook. useEffect(() => { edito ...

FlexBox responsive items that are expandable getting cut off

I am currently working on creating a row of expandable items. While I have almost achieved the desired behavior, there are a few issues that I need help with: On Desktop, the items are cut off and not fully visible. On Mobile, half of the items are missin ...

How can I properly address ReactJS Useeffect missing dependency problems when using componentDidMount in a component?

all Every day while I work on React Function Components, I encounter the same issue. It's a useEffect dependency problem. My workflow involves fetching data by calling a RestAPI as follows: Define useEffect with an empty array [] for the component ...

Is there a way to have a button function as a submit button for a form even when it is located in a separate component within a react application?

I am in the process of creating a user-friendly "My Account" page using react, where users can easily update their account information. I have divided my components into two sections: the navbar and the form itself. However, I am facing an issue with the s ...

Testing a state update in a Functional Component using React and Enzyme

I'm having trouble grasping the concept of triggering a state update that can be confirmed. My focus is on testing 2 specific cases related to the visual appearance of a button. 1) Testing if the button changes visually when selected 2) Testing if th ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

Discover the secret to prompting iOS 12 Autofill to request password saving within a React Native application

ISSUE I am currently using React Native 0.59.9 and have implemented a login screen in my mobile app with the intention of utilizing iOS 12's autofill feature to save passwords for new users. However, despite setting up the necessary configuration, th ...

Adding Bootstrap to container-specific styling in SCSS

I am currently in the process of upgrading to the most recent version of reactstrap & Bootstrap. Previously, I had reactstrap in my package.json file and downloaded Bootstrap SCSS in my client/src/styles/bootstrap directory. Now, my updated package.json c ...

Correcting the 1 pixel spacing issue in 3 containers each with a width of 33.333%

It is difficult to articulate, but I am noticing a 1 pixel line with 3 containers each having a width of 33.3333%. Unfortunately, this is not something I can change as it is part of the material-ui framework. <div class="container"> <div clas ...

"Troubleshooting: Issue with React Bootstrap accordion defaultActiveKey function not

Here is a sandbox example I created to demonstrate the issue: https://codesandbox.io/s/react-bootstrap-accordion-14pcp I'm working on setting up an accordion with a defaultActiveKey, but I'm having trouble getting it to work. Below is the code s ...

Ensure that each value in the MUI autocomplete appears on a separate line

I am working with a multi-select MUI Autocomplete component and I want the selected options to appear on separate lines for better readability, but I'm not sure how to achieve this. Currently, it looks like this: https://i.stack.imgur.com/PzOak.png ...

Retrieve the value of a Material UI Slider during the onDragStop event

As I work with a Material UI Slider in my React app, I am aiming to trigger the event onDragStop instead of onChange</code to reduce the number of times the event is fired. However, according to the <a href="https://mui.com/material-ui/react-slider" ...

Modify the color of a div element in React when it is clicked on

My goal is to change the color of each div individually when clicked. However, I am facing an issue where all divs change color at once when only one is clicked. I need help in modifying my code to achieve the desired behavior. Below is the current implem ...

React - Customizable Counter Components - Control All Counters with Parent Component

Hello everyone, I'm fairly new to React and still in the learning process. Currently, I have a challenge that involves creating a simple React Counter app with some specific requirements. The challenge is to build the app without using Redux or hooks. ...

Traversing through the BottomTabBar within a nested Stack Navigator results in an increased number of renders compared to

I have configured a bottom tab bar with a screen that I want to be hidden from the tabs, meaning it should not show up as a tab. To achieve this, I created a Native Stack and set the initial screen of that stack to the bottom tab stack. However, when I nav ...

Access and play audio files from a blob storage using Azure Functions in a React application

I have been working on integrating an audio file from azure storage into my react app using the react-h5-audio-player library. Below is the code snippet of my azure function: import { AzureFunction, Context, HttpRequest } from "@azure/functions" ...

Margins are added to cards on the right side

Looking for some help to improve the display of three cards in a grid. The card media has a max-width of 345px, but this is causing excessive margin-right space and making the styling look poorly. Any suggestions on how to eliminate this extra margin? If ...

Mastering socket emission and disconnection in reactjs

When using the onchange function, I am able to open a socket and emit/fetch data successfully. However, a new socket is opened on any event. I need to find a way to emit data from the same socket ID without opening a new socket each time. Could you pleas ...