Home > front end >  Change the visibility of a react component
Change the visibility of a react component

Time:09-22

Hi the following code should modify the visibility of a react component depending on whether or not a button is clicked, this when a button is clicked the first element must disappear and I have to appear the second, but this does not happen what is this due to?

React code:

import React from "react";
import styled from "styled-components";
import image from "../../assets/img/calc.png";
import CalculatorContainer from "./CalculatorDraggable/index";

class DraggableCalculator extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isCalculatorVisible: false };
  }
  enable() {
    console.log("Make calculator visibile");
    this.setState({
      isCalculatorVisible: true,
    });
  }
  render() {
    return (
      <p>
        {this.state.isCalculatorVisible == true ? (
          <CalculatorContainer />
        ) : (
          <p></p>
        )}
        <Container onClick={this.enable}>
          <img
            key={Math.random()}
            src={image}
            alt="help"
            width={120}
            height={220}
            style={{ marginLeft: 20 }}
          />
        </Container>
      </p>
    );
  }
}

export default DraggableCalculator;

const Container = styled.div`
  border-radius: 25px;
  border: 2px solid #73ad21;
  padding: 20px;
  width: 200px;
  height: 200px;

  /* background-color: var(--cLight2);
  border: 5px solid var(--cMain); */
  border-radius: 50%;
  margin-left: auto;
  margin-top: 30px;
  margin-right: auto;
  cursor: pointer;

  // @MEDIA TABLET LANDSCAPE
  @media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
    width: 100px;
    height: 100px;
  }

  img {
    max-width: 100%;
    max-height: 100%;
  }
`;

CodePudding user response:

It looks like the enable function doesn't have the this of the class component bound to it, it throws an error TypeError Cannot read properties of undefined (reading 'setState').

Either bind this to it in the constructor

constructor(props) {
  super(props);
  this.state = { isCalculatorVisible: false };
  this.enable = this.enable.bind(this); // <--
}

or convert to an arrow function so it happens automatically

enable = () => {
  console.log("Make calculator visible");
  this.setState({
    isCalculatorVisible: true,
  });
}

Edit change-the-visibility-of-a-react-component

CodePudding user response:

Your code is not working because "this" is undefined inside the enable() function. It so because React component (DraggableCalculator, in your case) does not auto-bind its methods to itself.

Hence you have to bind any method yourself inside the constructor, like this for your case:

constructor(props) {
    super(props);
    this.state = { isCalculatorVisible: false };

    this.enable = this.enable.bind(this);
}
  • Related