Reputation: 576
am having a trouble
i do have a popup in my BrowseModalUpload
component and i had given state as
class BrowseModalUpload extends React.Component {
constructor(props) {
super(props)
this.state = {
modalIsOpen: this.props.browseAssetComponent ? this.props.browseAssetComponent : false,
...
}}
So initially there is no popup and when you click on one link , setState
modalIsOpen to true and modal opens-thats the normal flow
And when i click in close window ,it setState
modalIsOpen
to false.
So i just clicked on popup it came and i click on close button it goes ,now i click this popup from different component having prop browseAssetComponent as true ,it didn't open up
code for modal is like this
<Modal transparent isOpen={this.state.modalIsOpen} onAfterOpen={this.afterOpenModal} onRequestClose={this.closeModal} ariaHideApp={false}>
this this.state.modalIsOpen is still false,it not gets updated when i call the same from another component and this popup not coming up.
if you guys need more information let me know. any help will be way to solve my roadblock
Upvotes: 1
Views: 2403
Reputation: 154
By doing this,
constructor(props) {
this.state = {
foo: props.foo
}
}
you just initialized a state from a prop. React doesn't sync the value of this.state.foo with this.props.foo for you.
If you want to change your state when props are changed, you can do it in getDerivedStateFromProps.
static getDerivedStateFromProps(props, state) {
return { foo: props.foo };
}
However, if you read the document of getDerivedStateFromProps carefully, you'll find React doesn't recommend to use this method in most of the situations. From your code, I don't really understand why this.props.browseAssetComponent
would affect this.state.modalIsOpen
. If you post the whole code I can give further suggestion.
Upvotes: 0
Reputation: 1685
You can use componentDidUpdate lifecycle method where you can set the state based on the props.
class BrowseModalUpload extends React.Component {
constructor(props) {
super(props)
this.state = {
modalIsOpen: this.props.browseAssetComponent ? this.props.browseAssetComponent : false,
...
}
componentDidUpdate(prevProps){
if(this.prevProps.browseAssetComponent != this.props.browseAssetComponent)
this.setState ({
modalIsOpen: this.props.browseAssetComponent ? this.props.browseAssetComponent : false)
}}
}
Upvotes: 1
Reputation: 9779
Don't define your props in state.
Better to pass directly like this
<Modal transparent isOpen={this.props.modalIsOpen} onAfterOpen={this.afterOpenModal} onRequestClose={this.closeModal} ariaHideApp={false}>
and handle from parent component function like this
handleModel=()=>{
this.setState(prev=>({modalIsOpen:!prev.modalIsOpen}));
}
Check this example https://codesandbox.io/s/model-popup-o1z0p. I hope it will help you.
Upvotes: 0