W
W
Wasya UK2018-10-20 15:02:32
React
Wasya UK, 2018-10-20 15:02:32

How to open modal window in React?

I have a separate button that should open a modal, but the opening state itself is in the modal's class. How to change the state from the outside?

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpen: false
    };
  }

  handleSubmit (e) {
    e.preventDefault();
  }

  showTradeModal = () => {
    this.setState({ isOpen: true });
  }

  closeTradeModal = () => {
    this.setState({ isOpen: false });
  }

  render() {
    return (
      <Modal isOpen={this.state.isOpen} style={tradeOptions}>
        <h2 ref={subtitle => this.subtitle = subtitle}>Hello</h2>
        <div>I am a modal</div>
        <form onSubmit={this.handleSubmit}>
          <input />
          <button>tab navigation</button>
          <button>stays</button>
          <button>inside</button>
          <button>the modal</button>
        </form>
        <button onClick={this.props.buyCurrency}>Confirm</button>
        <button onClick={this.closeTradeModal}>Cancel</button>
      </Modal>
    );
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nakree, 2018-10-20
@dmc1989

class Container extends React.Component {
  state = {
   showModal: false
  }

  handleModal = () => {
    this.setState({showModal: !this.state.showModal});
  }
render() {
  return (
    <Fragment>
      { this.state.showModal && <MyModal handleModal={this.handleModal}/> }
      <button onClick={this.handleModal}> Show modal </button>
    </Fragment>
   )
}

You can open from the outside, and close the modal in the modal itself.
Similarly, you can add more fields in the state and a couple of handlers to get as many modals as you like in one component.

R
Roman Alexandrovich, 2018-10-20
@RomReed

try like this

import Modal from "./Modal"

showModal(){
this.modal. showTradeModal()
}
render(){
<View>
<Button onClick={()=>this.showModal}
<Modal  ref={modal=>this.modal=modal}/>
</View>
}

R
real2210, 2018-10-22
@real2210

https://reactjs.org/docs/portals.html
Check out. documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question