So, I am trying to figure out the best way to do this:
Showing a modal or hiding a modal in react. On my main page I have a lot of photos and my current state setup is:
export default class Main extends TrackerReact(Component) {
constructor(props) {
super(props);
this.state = {
showModal: false,
modalPhoto: {},
};
this.close = this.close.bind(this);
this.open = this.open.bind(this);
}
close() { this.setState({ showModal: false }); } // basic modal close
open(e) {
this.setState({ modalPhoto: e });
this.setState({ showModal: true });
}
When I set showModal to true, it passes to the bootstrap-react modal:
<Modal
show={this.props.show} >
// ...loads modalPhoto form main state.modalPhoto
</Modal>
Problem: Every time I open the modal, it changes the main state and re-renders the main page. What is the best practice way to stop this re-render from happening? I tried:
// in the main component
shouldComponentUpdate(nextProps, nextState) {
if (this.state.showModal !== nextState.showModal) {
return false;
} else {
return true;
} // PS. I know this is wrong, but I was desperate...
I was also considering going around the outside with jquery and manually show the modal or hide the modal and thus not change state. The problems with this are obvious, Unmount and ReceiveProps is hard to maintain.
I also know that TrackerReact package will re-render if data changes, but no data should be changing with modal open and close.
Thoughts?
In React, every state variable is attached to a particular component instance. In this example, we have a single piece of state, count , which is associated with the Counter component. Whenever this state changes, Counter re-renders.
Using React DevTools to highlight what components rerendered To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.
You can add a condition in the call back function that checks if a certain condition is met, e.g. if data is empty. If it is empty, then fetch data, otherwise do nothing. This will prevent the infinite loop from happening. const getData = useEffect(()=>{ const fetchData = () => { UserService.
Maybe you should consider using a component to wrap your modal and manage the state. Your main component would not be updated anymore.
As said in the comments above, refreshing the view as soon as the state has been updated is the way React works
Dan Abramov has written a very interesting answer on Stack Overflow on how to deal with Modals with a redux state: How can I display a modal dialog in Redux that performs asynchronous actions?
Try to get some inspiration from this article.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With