2
votes

I am trying to code a react component for a modal and getting the error: "Uncaught TypeError: this.setState is not a function" when the openModal() is called. Below is my code:

class Header {

  constructor() {
      this.state = { showModal: false };
  } 

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

  closeModal() {
      this.setState({showModal: false});
  }

  render() {
    return (
      <div className="Header">
        <ModalDialog heading="heading" show={this.state.showModal}>
          <p>Body</p>
        </ModalDialog>
        <div className="Header-container">
          <Navigation className="Header-nav" />
          <div className="Navigation2">

            <Button bsStyle='primary' onClick={this.openModal.bind(this)}>Sign in</Button>

            <Button bsStyle='info' href="/register" onClick={Link.handleClick}>Sign up</Button>

          </div>
        </div>
      </div>
    );
  }

}

class ModalDialog {

  render() {
    if (this.props.show) {
        return (
        <div className="Overlay">
          <Modal heading={this.props.heading}>
            <div>{this.props.children}</div>
          </Modal>
        </div>
      );
    }
    return null;
  }
};

class Modal {

  render() {
    return (
      <div className="Modal effect">
        <h3>{this.props.heading}</h3>
        <div className="content">
          {this.props.children}
        </div>
      </div>
    );
  }
};

I am also trying to pass in a className into the element <div className="Modal effect"> from the Header component to change the dimensions of the Modal, is this possible?

Would be great if somebody could help me out with this. I am just starting out with React. Thanks

2
I managed to fix it, had to add super() above the code. But regarding passing classes into the component. is there a solution for this? Thankshilarl

2 Answers

2
votes

I am also trying to pass in a className into the element from the Header component to change the dimensions of the Modal, is this possible?

This is typically what props are made for, passing static information such size. So simply pass your class/size/staticprops as a prop like this:

<ModalDialog size={//whatever you need} className="Modal effect"/> 

From ModalDialog pass it to Modal

<Modal size={this.props.size} />

And then you just have to use it inside your Modal for whatever purpose you want. More about props in general :https://facebook.github.io/react/docs/transferring-props.html

Hope it helps

0
votes

I'm not familiar with reactJS but this looks wrong to me:

constructor() {
      this.state = { showModal: false };
}

Should it be:

constructor() {
      this.setState = ({ showModal: false });
}

?

Otherwise your Header class sets its state attribute to { showModal: false }

Which obviously has no 'setState' member function.