0

I'm fairly new to React, and I am currently having some trouble using the react hooks. I initialize show and setShow in the constructor, yet I get an error saying that show and setShow are undefined in the render function. I have something like:

export default class Projects extends Component {
  constructor(props) {
    super(props);
    const [show, setShow] = useState(false);    //Where I initialize show and setShow
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);
  }

  render() {
    return (
      <div class="projects-section" id="projects">
        <img className="project-image" src="assets/UAS-frontend.png" onClick={handleShow}/>
        <Modal show={show} onHide={handleClose}>    //Where I get the error
          <Modal.Header closeButton></Modal.Header>
          <Modal.Footer>
            <Button variant="secondary" onClick={handleClose}>
              Close
            </Button>
            <Button variant="primary" onClick={handleClose}>
              Save Changes
            </Button>
          </Modal.Footer>
        </Modal>
      </div>
    )
  }
}
2

1 Answer 1

1

React hooks for state management are used in function components. In your case you can go with the old school state object:

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

If you want to use React Hooks instead do this:

const Projects = (props) => {
  const [show, setShow] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  return (
    <div class="projects-section" id="projects">
      <img className="project-image" src="assets/UAS-frontend.png" onClick={handleShow}/>
      <Modal show={show} onHide={handleClose}>    //Where I get the error
        <Modal.Header closeButton></Modal.Header>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </div>
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

OMG. Half a year is now "old school"
Good ol' times @YuryTarabanko

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.