Reputation:
I am building an app with React v0.14.6 . The desired functionality is to click on the GoalItem to show the ModalItem. The goal-item has an 'a' tag with attribute onClick that sets {this.state.showModal: true}. The ModalItem is passed GoalItem's this.state.showModal via a showModal attribute.
To change the state of the ModalItem component such that this.state.showModal: this.props.showModal, I use setState() in componentWillReceiveProps.
The strange behavior is that the 'a' tag in GoalItem needs to be clicked twice to make the modal appear.The goal is for just one click to suffice.
Thank you in advance for your help. Below is the relevant code.
//goal-item.jsx
var React = require('react');
var ModalItem = require('./modal-item');
module.exports = React.createClass({
getInitialState() {
return {
name: this.props.goal.name,
nameChanged: false,
showModal: false
}
},
open() {
this.setState({ showModal: true });
},
render() {
return <a className="list-group-item"
key={this.props.goal.id}
onClick={this.open}>
<ModalItem goal={this.props.goal} showModal={this.state.showModal} />
</a>
}
});
//modal-item.jsx
var React = require('react');
var Modal = require('react-bootstrap/lib/modal');
var Button = require('react-bootstrap/lib/button');
module.exports = React.createClass({
getInitialState() {
return {showModal: false };
},
componentWillReceiveProps() {
this.setState({ showModal: this.props.showModal });
},
close() {
this.setState({ showModal: false });
},
render() {
return (
<div>
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>{this.props.goal.name}</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>{this.props.goal.description}</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>Close</Button>
</Modal.Footer>
</Modal>
</div>
);
}
});
Upvotes: 1
Views: 1748
Reputation: 3277
In the componentWillReceiveProps
you will get new props as argument.
So it should be:
componentWillReceiveProps(newProps) {
this.setState({ showModal: newProps.showModal });
}
Basically this is a place where you can compare new props from argument with old prop by accessing them using this.props
, and then perform needed updates of state.
See documentation: componentWillReceiveProps
Upvotes: 2