React state update not triggering a component re-render

I've been attempting to toggle the visibility of a div by clicking on another div, but I'm encountering an issue. The div becomes invisible on the first click only if it was visible initially. After that, it remains invisible and does not update. However, the state is still being toggled in the console.

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(){
    super()
    this.state = {
      vis: '0'
    }
  }

  toggleVisibility=()=>{
    console.log("toggle login", this.state.vis)
    if(this.state.vis === "hidden"){
      console.log('showing')
      this.setState((state, props)=>({vis:'0'}))
    } else {
      console.log('hiding')
      this.setState((state, props)=>({vis:'hidden'}))
    }
  }

  render() {

    const styles = {
      visibility: this.state.vis
    }

    return (
      <div className="App">
        <div className="salebar"><a className="salebar sale" 
href="login">Click here!</a></div>
        <div className="navbar">
            <div className="nav"><div className="nnav">JMZ</div></div>
            <div className="nav2"><div className="nnav2">PRODUCTS</div></div>
            <div className="loginContainer"><div className="login" onClick={this.toggleVisibility}>LOGIN/SIGN UP</div></div>
        </div>
        <div className="login-container">
          <div className="lognester">
            <div style={styles} className="login-tab">
              <input className="user" type="text" placeholder="Username"/>
              <input className="password" type="password" placeholder="Password"/>
              <button className="user">Login</button>
          Sign in or <a className="register-link" href="register">register</a> a new account.
            </div>
          </div>
        </div>
        <div className="intro-pics"></div>
        <div className="content"></div>

        <audio preload loop controls autoPlay className="audio">
          <source src="https://memefly.me/i/toValhalla.mp3"/>
            Your browser does not support the audio element.
        </audio>
      </div>
    );
  }
}


export default App;

Answer №1

Give this a try:

class Website extends Component {
  constructor() {
    super();
    this.state = {
      showMenu: true
    };
  }
  toggleMenu = () => {
    this.setState({ showMenu: !this.state.showMenu });
  };
  render() {
    return (
      <div className="Website">
        <div className="header">
          <a className="salebar sale" href="login">
            Click here
          </a>
        </div>
        <div className="navigation">
          <div className="menu">
            <div className="brand">JMZ</div>
          </div>
          <div className="menu2">
            <div className="product-menu">PRODUCTS</div>
          </div>
          <div className="userAccount">
            <div className="user-login" onClick={this.toggleMenu}>
              LOGIN/SIGN UP
            </div>
          </div>
        </div>
        <div className="login-section">
          <div className="login-box">
            {this.state.showMenu ? (
              <div className="login-tab">
                <input className="username" type="text" placeholder="Username" />
                <input
                  className="password"
                  type="password"
                  placeholder="Password"
                />
                <button className="submit-button">Login</button>
                Sign in or{' '}
                <a className="register-link" href="register">
                  register
                </a>{' '}
                a new account.
              </div>
            ) : (
                ''
              )}
          </div>
        </div>
        <div className="intro-images" />
        <div className="content-section" />
      </div>
    );
  }
}
export default Website;

View the demo here: https://codesandbox.io/s/72zzk2xr70

Answer №2

Your code has a couple of issues that need to be addressed

  1. Make sure to use visibility:visible instead of visibility: 0. Please update this in your code.
  2. Avoid setting state within the render function at all costs, as it is considered a very poor practice.

Answer №3

1 ) The method togHide can be declared above the render function like this:

toghide = () => {
//your code
}

render(){...}

2) A better way to handle visibility condition is by using boolean logic with true/false on your vis state. You can do it as follows:

 constructor(){
        super()
        this.state = {
          vis: true
        }
      }


toghide = () => {

if(this.state.vis){

this.setState({
vis : false

})}

else{
this.setState({
vis : true
})}

3) When using the toghide method, you can apply the same setState code demonstrated above. It's unnecessary to pass props if not used, and there's no need for a return statement in setState.

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

The transition effect is not functioning properly in CSS and React.js

.cartBtn { appearance: none; outline: none; border: none; cursor: pointer; text-align: center; background-color: transparent; color: inherit; } .cartBtn:hover { color: black; } .cart { display: none; opacity: 0; transition: all 4s ea ...

The presentational component undergoes constant re-rendering

UPDATE: After thorough investigation, I have identified the issue. It seems to be related to the code snippet in the third component that I shared earlier. The main problem lies in the function calls for goToBook and selectBook. My goal is to enable users ...

What is preventing you from utilizing TypeScript's abstract classes for generating React factories, especially when regular classes seem to function properly?

Here is an example showcasing the behavior of TypeScript code using React with abstract classes: import * as React from "react"; class MyComponent<P> extends React.Component<P, any> { static getFactory() { return React.createFacto ...

Is there a way for me to position my chat messages on the right side in the chat room?

I have a react chat application and I'm looking to customize the appearance of my messages. Currently, all entries with an orange vertical bar belong to me and are displayed on the left side of the chat room. I would like to move them to the right sid ...

Can you tell me how to add a variable to an array of objects in JavaScript?

I am currently engaged in a small project aimed at: Reading data from a CSV file (such as employee names and shifts) Displaying this data on FullCalendar. How can I incorporate the CSV result into this line of code: { id: 'a', title: 'Audi ...

guiding user immediately to blog post upon successful login

I recently created a blog with a customized URL like instead of the traditional . Now, my dilemma is that I want to share this URL and have it redirect users to the login page if they are not logged in. Once they log in, I would like them to be redirect ...

Utilizing Regular Expressions in Express.js Routes

Is there a way to extract a specific value from my URL using Express? For example, my URL structure is as follows: host/:value.schema I need to retrieve the value from this URL. Here's an example: host/horse.schema (In this case, the value wo ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

Using Formik with React-phone-input-2 causes the values to return as an empty string

Is there a way to integrate Formik with React-Phone-Input-2 in the phone field without encountering issues related to HandleChange, HandleBlur, and values.phone being submitted as an empty string? How can this be effectively managed? import { useFormik } ...

The building process of Ember encountered an error due to a problem with the broccoli builder

I'm currently working on an Ember project and facing an issue while trying to upgrade the version from 2.8 to 3.5.0. After changing the version and some dependencies, I encountered the following error : Error stack Even after attempting to resolve i ...

Issue encountered with sortable table in list.js

Encountering a puzzling error while implementing list.js and tabletop for a sortable table sourced from a Google Doc. The error message reads: "Uncaught TypeError: Cannot read property 'childNodes' of undefined," pinpointing the first line in lis ...

Tips for updating Ref objects in React

In the process of fixing a section of my project, I'm encountering an issue where I have no control over how refs are being utilized. The Editable text elements are currently handled through refs and a state variable within the component that holds al ...

What is the best way to implement two for loops in a Django template to handle sending and receiving chat messages efficiently?

I am attempting to implement sending and receiving messages in a Django template using a for loop. Here is my views function: @login_required def message_form(request, id, slug, user_id): user2 = request.user user_id = user_id user = get_objec ...

Dealing with mistakes in a contact form - Finding the correct function

I developed a form using material-ui in React. I am facing some issues with my submit function. I am using a snackbar to notify the user about the successful submission, as well as a snackbar to alert them about missing required fields. The problem arise ...

What is the reason for the child component having a greater number of props compared to the parent component

I am facing an issue with my parent component and child component in React. The child component seems to have more props data than the parent component. Parent component: import React, { Component} from 'react'; import { Link } from 'react ...

Using Python and Selenium to Scroll Down the Page (with Two Separate Scrollbars)

I need help scrolling down the conversation section on Facebook Messenger. There are 2 scroll bars on the page, and I specifically want to scroll down scroll bar number 1 (see image) Click this link to access the page (make sure you are logged in and hav ...

What is the process for providing personalized qualifications?

Hello, I have set up my NextAuth configuration as shown below: import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" export default NextAuth({ providers: [ CredentialsProvider({ ...

React and Material-Ui utilize class definitions in .js files, which are then passed as strings to components

I am attempting to define a class within my .js file in order to utilize the material-ui theme object and pass it as a string to a component since the component's prop only accepts strings. Unfortunately, the React-Dropzone import does not accept a cl ...

Iterate over a JSON object to calculate the total sum of values based on distinct nested properties

Here is a JSON object that contains cost and author information. I am working on this in Express.js and using Underscore. [ { "Cost": 250, "author": { "id": "2", "name": "Joe", "workId": "5" } }, { ...

Saving an image in Flask and securely storing it in a local directory

I am looking to implement a functionality where I can upload an image and pass it to the Python code in Flask for local storage. While following a tutorial, I encountered an issue with the query as the request always returned 'No file part': if & ...