noblerare noblerare - 8 months ago 75
React JSX Question

Cannot read property 'setState' of null - React.js, Modal, Bootstrap

I am trying React.js for the first time in trying to build this web app. I am getting

Cannot read property 'setState' of null
on the specified line below. I've been trying to figure out why for the past few hours and cannot seem to figure it out. Any help would be greatly appreciated.


import React from 'react';
import { Modal, Button, ButtonToolbar } from 'react-bootstrap';

export default class MyModal extends React.Component {
constructor(props) {
this.state = {show: false};

showModal() {
this.setState({show: true});

hideModal() {
this.setState({show: false});

render() {
return (
<Button bsStyle="primary" onClick={this.showModal}>
Launch demo modal

<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-lg">Modal heading</Modal.Title>
<h4>Wrapped Text</h4>
<Button onClick={this.hideModal}>Close</Button>
</Modal.Footer> // Chrome inspector says it errors on this line
} // end render function

} // end export default

Answer Source

bind your component class methods inside the constructor() (binding inside constructor is better than binding inside render() for performance sake):

constructor(props) {
    this.state = {show: false};
    this.showModal = this.showModal.bind(this);
    this.hideModal = this.hideModal.bind(this);