The use case is that I want to map the root (/) to one of two different components based on whether the user is logged in or not, and I want these two components to reside in different bundles and lazily loaded, so simply putting the login check in the render() method would not do.
I tried to use dynamic route definition with require.ensure() to lazily load the component, and it works for the first time, but after changing the login state the component doesn't get updated (even if I navigate to another route and back to / ). I tried to force re-rendering the router by setting props on the component that contains the router, both manually and by making it a Redux connected component, and I also tried to add a listener to the Redux store and change the component state in response to login change, but in all of the attempts I got the error "You cannot change ; it will be ignored" and the component doesn't change.
My ugly solution is to have the different component loading code outside of the router, listen to the login state change and in response load the matching component and set it in the wrapping component's state, which is referenced in the render() code. Is there a clean "React-Router-ish" way to do what I want?
How to Load Components Conditionally in ReactJS 1 Introduction. In this guide, you'll learn how to optimize React applications by loading components conditionally, or only when they are required. 2 Use Case. ... 3 Start with Creating the Headers. ... 4 Lazy Loading <DesktopHeader /> Component. ... 5 Complete Source Code. ... 6 Conclusion. ...
For eg, In a University Information System, when a teacher logins, then different components are rendered whereas when student logins, different components are rendered. This is called Conditional Rendering of React Components. Conditional Rendering: To create multiple components and render them based on some conditions.
When UI is designed using React, we come across a situation when components are to be rendered on the screen based upon some condition. For eg, In a University Information System, when a teacher logins, then different components are rendered whereas when student logins, different components are rendered.
In this guide, you'll learn how to optimize React applications by loading components conditionally, or only when they are required. The concept of loading components dynamically during runtime is called lazy loading.
React Router 4 pretty much solves this as it made the route configuration part of the component rendering, so having conditional rendering is the same whether it's based on the location or on other props/state.
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