Answer the question
In order to leave comments, you need to log in
How to correctly change the state of a child (or call functions) from a parent in React.Js?
How to correctly change the state of a child (or call functions) from a parent in React.Js?
This question arose when implementing the following logic:
there is a "registration" button, when clicked, a dialog box should appear with fields for registration and a "confirm" button. When I click the "confirm" button, I need to execute for example the signup function at the end of which I need to close this dialog box.
My current implementation using react-bootstrap:
ModalInstance.js:
import React from 'react';
import { Button, Modal } from 'react-bootstrap';
const ModalInstance = React.createClass ({
getInitialState() {
return { showModal: false };
},
close() {
this.setState({ showModal: false });
},
open() {
this.setState({ showModal: true });
},
render() {
return (
<div id={this.props.id}>
<Button bsStyle="primary" onClick={this.open}>{this.props.buttonName}</Button>
<Modal ref="modal" show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>{this.props.title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.props.children}
</Modal.Body>
</Modal>
</div>
);
}
})
module.exports = ModalInstance;
...
const Header = React.createClass ({
signup() {
...
let modal = this.refs.modal;
modal.close();
},
render() {
...
<ModalInstance
ref="modal"
id="signupModalButton"
title="Sign up"
buttonName="Sign up">
<form>
...
<Button bsStyle="primary" onClick={this.signup}>Sing up</Button>
</form>
</ModalInstance>
}
Answer the question
In order to leave comments, you need to log in
Make a SignupModal component that will represent a modal window for registration with all the parameters and buttons. And then pass a function to it to be called when the button is pressed.
class SignupModal ... {
...
handleSignupButton(){
// do something
if(this.props.onSignup)
this.props.onSignup()
}
render(){
...
<Button .... onClick={this.handleSignupButton} />
...
}
}
class SomeComponent ... {
...
handleSignup(){
// do something
}
render(){
...
<SignupModal ... onSignup={this.handleSignup} />
...
}
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question