Adjust the component's onClick property in Next.js

Looking for guidance on how to update a property value of a component in Next.js. I have been using the Material-UI library for styling.

Encountering an issue when attempting to modify the 'open' property of a drawer component, as it constantly displays a [TypeError] stating that 'open' is read-only.

const drawer = (
  <SwipeableDrawer open={drawerOpened}>
    <div tabIndex={0} role="button">
      {sideList}
    </div>
  </SwipeableDrawer>
);

const handleClick = e => {
  drawerOpened = !drawerOpened;
  drawer.props.open = drawerOpened;
  e.preventDefault();
};

const Index = () => (
  <div className={styles.root}>
    <AppBar position="static">
      <Toolbar>
        <IconButton
          className={styles.menuButton}
          color="inherit"
          aria-label="Menu"
          onClick={handleClick}
        >
          <MenuIcon />
        </IconButton>
        <Typography variant="h6" color="inherit" className={styles.grow}>
          Example
        </Typography>
        <Button color="inherit" style={{ right: "0px", position: "absolute" }}>
          Login
        </Button>
      </Toolbar>
    </AppBar>
    {drawer}
  </div>
);

Answer №1

It is unclear where the drawerOpened variable was declared. However, once the value of drawerOpened is toggled, the prop for drawer will be updated, eliminating the need to modify drawer.props.open:

const handleClick = e => {
  e.preventDefault();
  drawerOpened = !drawerOpened;
};

In addition, it is recommended that the component Index be a React Class instead of a functional component, with the state including drawerOpen as a property passed down to drawer. The handleClick function should update the state using setState:

class Index extends React.Component {
  state = {drawerOpened: false}

  handleClick = e => {
    e.preventDefault();
    this.setState(prevState => ({
      drawerOpened: !prevState.drawerOpened
    }))
  };

  render() {
    return <div className={styles.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton
            className={styles.menuButton}
            color="inherit"
            aria-label="Menu"
            onClick={this.handleClick}
          >
            <MenuIcon/>
          </IconButton>
          <Typography variant="h6" color="inherit" className={styles.grow}>
            Example
          </Typography>
          <Button color="inherit" style={{ right: "0px", position: "absolute" }}>
            Login
          </Button>
        </Toolbar>
      </AppBar>
      <SwipeableDrawer open={this.state.drawerOpened}>
        <div tabIndex={0} role="button">
          {sideList}
        </div>
      </SwipeableDrawer>
    </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

Getting the most out of geometry vertices with Threejs: mastering partial transforms

In my current project, I am working with a mesh that consists of approximately 5k vertices. These vertices have been merged from multiple geometries into a flat array. Initially, I was able to modify individual vertices successfully by setting the flag `ve ...

I'm just starting to explore async programming. Can someone explain how to ensure proper sequencing of events across multiple objects?

Currently, I am in the process of revamping my program. Initially, I managed to make it function by using synchronous AJAX calls, but I now wish to do things the correct way. The issue arises when the headline is supposed to be created with a new headline ...

How to effectively test a form submission with an external API using React, Jest, and Enzyme?

I have integrated a geocoding API to verify address submissions on a form. Upon submitting the form, the geocoding API is called first, followed by validation of the remaining form fields. class Form extends React.Component { geocode = (streetAddress, cit ...

Tips for implementing event handlers on dynamically generated li elements in VueJS

Creating multiple ul elements using v-for in the following way <div v-for="item in info"> <ul> <li><a>{{item.number}}</a></li> <li><a>{{item.alphabet}}</a></li> </ul> </div&g ...

Popper.js enhances the appearance of the input field label

When the placement of a tooltip created by Popper.js and overlaying a material-ui input field flips to the top, how can we prevent this overlay? Here is an example of the Popper code: <Popper id={id} open={open} anchorEl={this.state.anchorEl} ...

Is it possible to have the cursor rotate or animate by 45 degrees when clicked

Do you know how to create a unique custom cursor using CSS? Say, for example, we have this code: cursor: url(images/cursor.png) 15 15, auto; Now, what if we wanted to take it up a notch and make the cursor rotate -45 degrees when clicked, and then revert ...

You need to click the React onClick button twice in order to successfully trigger the API

I want to configure React so that when clicked, it will run process.env.REACT_APP_LOGOUT and remove the item set in local storage. Currently, it requires two clicks to execute. The first click redirects to the index page, and then a second click is needed ...

Determine whether the color is a string ('white' === color? // true, 'bright white gold' === color? // false)

I am facing an issue with multiple color strings retrieved from the database. Each color string needs to be converted to lowercase and then passed as inline styles: const colorPickerItem = color => ( <View style={{backgroundColor: color.toLowerC ...

Entering data into a webpage and retrieving the result from a designated cell in a Google Sheets document

Currently, I am in the process of developing a school platform and I am looking to incorporate a functionality that allows students to easily check the number of "passport" points they have earned. I envision having an input field along with a button that ...

The scope of this variable in Node.js results in an undefined response

Have you ever noticed the difference in behavior when executing JavaScript code in Google Chrome's console compared to running the same logic in a file using Node.js? function foo() { console.log( this.bar ); } var bar = "global"; foo(); In Chr ...

What type of technology is typically utilized in creating functional platforms such as goDaddy, wix, and other web design websites?

I am currently working on a web development project that aims to allow users to edit webpages without needing any coding knowledge. Users with authorization will be able to modify not only the text but also various HTML tags on the page, similar to platfor ...

Encountered a TypeError with mongoose: The function specified is not recognized as a valid function when attempting to create a new mongoose instance

I'm currently developing a web application using the MEAN stack, and I've encountered an issue with my mongoose instance that's giving me a headache. Let me share parts of my code: my route const express = require('express'); co ...

Sending AJAX data from VIEW to CONTROLLER in PHP (MVC) using AJAX: A step-by-step guide

I have a page at http://visiting/blog. The Controller contains two methods: action_index and add_index. When Action_index() executes, it returns pages with indexes. On the other hand, Add_index() invokes a model's method called add_data(), which inse ...

Template does not reflect changes made to filters in real-time

I've been working on filtering my "PriceList" collection and sorting is functioning perfectly. However, I'm experiencing some issues with implementing filters and search functionality. When I click on custom filter buttons, the template doesn&apo ...

Updating Documents in CouchDB

Can you please confirm if this is the correct method for updating a document in couchDB? To update a document (let's call it fooDoc), I must pass "_rev". First, I need to retrieve that document using the following code (foo.get). Then, in the callbac ...

Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function. I am seeking clar ...

`The Art of Binding() with Objects Created on the Fly`

Currently facing challenges with rebinding something using a dynamically created object from prepend. Despite trying several methods, I am only able to unbind. Seeking assistance. $(document).ready(function(){ $(".newdir").click(function(){ $(".d-exp ...

Implementing AngularJS to store data in a JSON object

Imagine having an animals.json file with the following details: { "animals": { "elephant": { "size": "large" }, "mouse": { "size": "small" } } } Now, let's say this data is being added to the controller scope: anim ...

Troubleshooting issue with the spread operator and setState in React, Typescript, and Material-ui

I recently developed a custom Snackbar component in React with Material-ui and Typescript. While working on it, I encountered some confusion regarding the usage of spread operators and await functions. (Example available here: https://codesandbox.io/s/gift ...

Clicking will cause my background content to blur

Is there a way to implement a menu button that, when clicked, reveals a menu with blurred content in the background? And when clicked again, the content returns to normal? Here's the current HTML structure: <div class="menu"> <div class=" ...