When to avoid conditional styles in React
A few examples of when it is not appropriate to use conditional styles in React.
05/20/2022
Web, React
Conditional Styles in React
One of the coolest features of React is the ability to conditionally render elements based on a condition. Styles can be applied conditionally. When you work on a complex project, you may find yourself writing conditional styles often for the tiniest bits of your User Interface.
Use cases for conditional styles
When the User Interface is tied to a very specific set of data that is based on authentication states or API specific data. For example, for a component displaying a UI Dashboard for a basic user and a UI Dashboard for a premium user, you may want to conditionally render nothing if not a premium user.
Why avoid conditional styles in this case?
One could easily use chrome developer tools to see the styles that are being applied to the component and be able to access the premium features, especially for those that depend on the UI logic to render specific UI elements.
One may argue that an API endpoint that returns a boolean value to determine if a user is a premium user or not could still prevent any malicious users from accessing the premium features. Well if the API endpoint is not secure or for any reason has no this capability built or fails, then the UI logic could be used to render the relevant UI elements using conditional styles (still not a good idea)
But using the two approaches together is much more recommended.
-
Using a conditional style
// 1. Bad. const Dashboard = () => { const { isPremium } = useContet(AuthContext); return ( <section> <PremiumFeature style={isPremium ? { display: "block" } : { display: "none" }} /> <OtherUIStuff /> </section> ); };
-
Avoiding conditional styles
// 2. Good. const Dashboard = () => { const { isPremium } = useContext(AuthContext); return ( <section> {isPremium ? <PremiumFeature /> : null} <OtherUIStuff /> </section> ); };
Author : Maye Edwin