Simone Rene
Simone Rene

Reputation: 25

ReactJS - Can I open open a Modal from different component

I am trying to call a model in "model.js" by onClick a button from another component (list.js) , just wonder if I have missed any step please see below:

model.js

import React from 'react';

class Model extends React.Component{

 render(){
  return(
   <div>
    //code inside the Model etc...  
    <Button onClick={this.submit.bind(this)}>Submit</Button>
   </div>
  )
 }
}

export default Model;

list.js

import Model from './model';
class List extends React.Component{
 render(){

  constructor() {
  super();

   this.toggleModal = this.toggleModal.bind(this);
   this.state = {
     open: false
   }
  }

  toggleModal() {
   this.setState({
   open: this.state.open
   });
  }

return(
 <div>
  <Button onClick={this.toggleModal}>Add</Button>
 </div>
 <div>
  <Model open={this.state.open} toggleModal={this.toggleModal}/>
 </div>
  )
 }
}

export default List;

I have tried many ways to change the event handler code in List , but it still doesnt work.

That would be much appreciate if you guys could give me a hand and point out where the problems are, so that i can move forward.

Upvotes: 0

Views: 2331

Answers (2)

hendrixchord
hendrixchord

Reputation: 5444

Why aren't you changing the state open value to either true or false

this.setState({
   open: this.state.open
});

The above code will always set the value as false. Maybe what you could do is !this.state.open

Upvotes: 1

kind user
kind user

Reputation: 41913

You definetely miss the exclamation mark, because as for now, you will always assign false value when clicking the button - modal won't show up.

this.setState({
  open: !this.state.open
});

Upvotes: 1

Related Questions