'Is it good practice for a react component to have returned value of null?
I've got a portal at the bottom of the screen just for informational purposes. It is displayed on a redux state and this component is at App level. Problem is with re-render of the entire parent component if this portal component changes its state. In my case, if someone closes the portal. Here's how I close the portal on a click.
dispatch({
type: 'close-portal',
payload: {
portalState: { display: false },
},
});
App component
const isPortalOpen = useSelector((state) => state.user.portalState.display);
<Switch>
<Route path='/login' component={LoginPage} exact />
<Route path='/error' component={PermissionErrorPage} exact />
</Switch>
{isPortalOpen && <InformativeMessage />}
Now If I am on the Login page and I close the portal, the entire page re-renders.
Alternative
I removed the conditional rendering from the App component and moved that into the portal component itself.
App component
<Switch>
<Route path='/login' component={LoginPage} exact />
<Route path='/error' component={PermissionErrorPage} exact />
</Switch>
<InformativeMessage />
Portal component
return (
<>
{isPortalOpen ? (
<EuiPortal>
<EuiBottomBar style={{ backgroundColor: showUnsavedWarningPortal ? 'red' : '', padding: '20px' }}>
<EuiFlexItem style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
<EuiFlexItem>
<EuiButtonIcon
onClick={closePortal}
color='ghost'
iconType='crossInACircleFilled'
/>
</EuiFlexItem>
<EuiFlexItem style={{ marginLeft: '10px' }}>
<EuiText>{message}</EuiText>
</EuiFlexItem>
</EuiFlexItem>
</EuiBottomBar>
</EuiPortal>
) : null}
</>
);
Dobut
Now this will return nullif the portal is closed but this component isn't completely removed. If I open up the Dev tools and head over to the Components tab I can able to see the portal component. Of course, there's nothing inside but is it a good practice to have this component through out the entire app is running?
Solution 1:[1]
I would say there is nothing wrong with it, and I have seen such technique being used a lot. Preferably, I like first approach more - it puts the logic in the App component, and the InfoMessage only need to care about its presentation - it is a nice way to do a bit of separation of concern
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bao Huynh Lam |
