{"id":3140,"date":"2023-05-19T06:28:57","date_gmt":"2023-05-19T06:28:57","guid":{"rendered":"http:\/\/the-codest.localhost\/blog\/component-visibility-in-react-with-conditional-rendering-and-guards\/"},"modified":"2026-03-05T10:47:23","modified_gmt":"2026-03-05T10:47:23","slug":"visibilite-conditionnelle-des-composants-dans-react","status":"publish","type":"post","link":"https:\/\/thecodest.co\/fr\/blog\/conditional-component-visibility-in-react\/","title":{"rendered":"Visibilit\u00e9 des composants dans React avec rendu conditionnel et protections"},"content":{"rendered":"\n<p>Today I would like to discuss how to control <strong>component visibility in <a href=\"https:\/\/thecodest.co\/fr\/blog\/react-development-all-you-have-to-know\/\">React<\/a><\/strong>. But before we start there is small<br>disclaimer:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">Presented solution is not very secure in meaning of protecting your application against \u201ehackers\u201d (whoever there are).\nRemember that you need to protect your endpoints and to use good practices in application design. This solution only\nmakes your work a little easier.\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Task, problem solution, or what we would like to achieve<\/h2>\n\n\n\n<p>One of the most common functionalities is to show component only for a bunch of users that have some specific rights,<br>roles or privileges. Common solution is to add some <code>if<\/code>s to <a href=\"https:\/\/thecodest.co\/fr\/dictionary\/what-is-code-refactoring\/\">code<\/a>, manually check conditions and show or not elements.<\/p>\n\n\n\n<p>Let take a look to <code>SimpleAppHeader<\/code> component that contains few navigation elements.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">&lt;!-- wp:paragraph --&gt;\n&lt;p&gt;&lt;code&gt;typescript jsx&lt;br&gt;\nexport const SimpleAppHeader: FC = () =&amp;gt; {&lt;br&gt;\n    return (&lt;br&gt;\n        &amp;lt;header&amp;gt;&lt;br&gt;\n            &amp;lt;nav&amp;gt;&lt;br&gt;\n                &amp;lt;ul&amp;gt;&lt;br&gt;\n                    {&lt;br&gt;\n                        currentUser.role === \"ADMIN\" &amp;amp;&amp;amp;&lt;br&gt;\n                        &amp;lt;li&amp;gt;Admin only component&amp;lt;\/li&amp;gt;&lt;br&gt;\n                    }&lt;br&gt;\n                    {&lt;br&gt;\n                        currentUser.role === \"USER\" &amp;amp;&amp;amp;&lt;br&gt;\n                        &amp;lt;li&amp;gt;User only component&amp;lt;\/li&amp;gt;&lt;br&gt;\n                    }&lt;br&gt;\n                    {&lt;br&gt;\n                        (currentUser.role === \"ADMIN\" || currentUser.role === \"USER\") &amp;amp;&amp;amp;&lt;br&gt;\n                        &amp;lt;li&amp;gt;Admin and User only component&amp;lt;\/li&amp;gt;&lt;br&gt;\n                    }&lt;br&gt;\n                    &amp;lt;li&amp;gt;General usage element&amp;lt;\/li&amp;gt;&lt;br&gt;\n                &amp;lt;\/ul&amp;gt;&lt;br&gt;\n            &amp;lt;\/nav&amp;gt;&lt;br&gt;\n        &amp;lt;\/header&amp;gt;&lt;br&gt;\n    )&lt;br&gt;\n}&lt;br&gt;\n&lt;\/code&gt;&lt;\/p&gt;\n&lt;!-- \/wp:paragraph --&gt;\n\n<\/code><\/pre>\n\n\n\n<p>Looks \u201enot bad\u201d. Probably you could encapsulate checks into functions to reduce complexity. <code>currentUser<\/code> is some object<br>that has <code>role<\/code> property, but it could be anything that we would like to use as subject of our control mechanism.<\/p>\n\n\n\n<p>This code has some problems. If <a href=\"https:\/\/thecodest.co\/fr\/dictionary\/why-do-projects-fail\/\">project<\/a> grows we probably use that constructions in many places. So we need to copy,<br>somehow, conditions. This code are hard to maintain and changing in a future. Specially when access rules change during<br>time e.g. we need to change <code>currentUser<\/code> into something else. It is very hard to test. You need to write many tests<br>just to verify if your condition is ok.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Simplification<\/h3>\n\n\n\n<p>Time to simplify this code a little. We could extract some methods and make code shorter and less complex:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">const isAdmin = (role: string): boolean =&gt; role === \"ADMIN\";\nconst isUser = (role: string): boolean =&gt; role === \"USER\";\nconst isAdminOrUser = (role: string): boolean =&gt; isAdmin(role) || isUser(role);\n\nexport const SimplifiedAppHeader: FC = () =&gt; {\nreturn (\n\n{\n\nisAdmin(currentUser.role) &amp;&amp;\nAdmin only component\n\n}\n{\nisUser(currentUser.role) &amp;&amp;\n\nUser only component\n\n}\n{\n(isAdminOrUser(currentUser.role)) &amp;&amp;\n\nAdmin and User only component\n\n}\n\nGeneral usage element\n\n)\n}\n```\n\n<\/code><\/pre>\n\n\n\n<p>Looks promising. We reduce noise od repeat lines. Code is more readable and easier to maintain. But take a look to<br>function <code>isAdminOrUser<\/code>. We have only two roles. If we introduce third role we need to create another set of functions<br>that combines roles. Time to another version.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Filtering<\/h3>\n\n\n\n<p>Let introduce function <code>hasRole<\/code> that will be replacement for our <code>isX<\/code> functions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">const hasRole = (role: string, requiredRole: string[]): boolean =&gt; {\nlet found: string | undefined = requiredRole.find(s =&gt; role === s);\nreturn found !== undefined;\n}\n\nexport const FilteringAppHeader: FC = () =&gt; {\nreturn (\n\n{\n\nhasRole(currentUser.role, [\"ADMIN\"]) &amp;&amp;\nAdmin only component\n\n}\n{\nhasRole(currentUser.role, [\"USER\"]) &amp;&amp;\n\nUser only component\n\n}\n{\nhasRole(currentUser.role, [\"ADMIN\", \"USER\"]) &amp;&amp;\n\nAdmin and User only component\n\n}\n\nGeneral usage element\n\n)\n}\n```<\/code><\/pre>\n\n\n\n<p>Now looks good. We still have conditions in html part of code, but now we can test <code>hasRole<\/code> function and trust that it<br>will be used with correct set of parameters. Adding or changing roles is now easier. We use array that contains all<br>roles that we need in place.<\/p>\n\n\n\n<p>However, this solution is bind to <code>currentUser<\/code> object. Assumption is that object is somehow global or easy to access in<br>any place in application. So we can try to encapsulate this. Of course, we can move it to <code>hasRole<\/code> function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\"><code> const hasRole = (requiredRole: string[]): boolean =&gt; {\n     let found: string | undefined = requiredRole.find(s =&gt; currentUser.role === s);\n     return found !== undefined;\n }<\/code><\/code><\/pre>\n\n\n\n<p>But that gives <a href=\"https:\/\/thecodest.co\/fr\/blog\/why-us-companies-are-opting-for-polish-developers\/\">us<\/a> almost nothing.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The <code>Guard<\/code> Component<\/h2>\n\n\n\n<p>Time to create component that encapsulate whole logic. I named it <code>Guard<\/code> and this is how I want to use it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\"><code><code> export const GuardedAppHeader: FC = () =&gt; {\n     return (\n         &lt;header&gt;\n             &lt;nav&gt;\n                 &lt;ul&gt;\n                     &lt;Guard requiredRoles={[\"ADMIN\"]}&gt;\n                         &lt;li&gt;Admin only component&lt;\/li&gt;\n                     &lt;\/Guard&gt;\n                     &lt;Guard requiredRoles={[\"USER\"]}&gt;\n                         &lt;li&gt;User only component&lt;\/li&gt;\n                     &lt;\/Guard&gt;\n                     &lt;Guard requiredRoles={[\"USER\", \"ADMIN\"]}&gt;\n                         &lt;li&gt;Admin and User component&lt;\/li&gt;\n                     &lt;\/Guard&gt;\n                     &lt;li&gt;General usage element&lt;\/li&gt;\n                 &lt;\/ul&gt;\n             &lt;\/nav&gt;\n         &lt;\/header&gt;\n     );\n }<\/code><\/code><\/code><\/pre>\n\n\n\n<p>Component need two properties. First <code>children<\/code> responsible for content that is guarded. Second <code>requiredRoles<\/code> that<br>handle array of roles that gives us access.<\/p>\n\n\n\n<p>We need representation of this struct. It is very simple. We extends type <code>React.PropsWithChildren<\/code> that has <code>children<\/code><br>property. Of course you can manually add that property to your type and omit extension.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">interface IGuardProps extends React.PropsWithChildren {\nrequiredRoles: string[];\n}<\/code><\/pre>\n\n\n\n<p>Component itself is simple too. We will reuse <code>hasRole<\/code> function here.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">export const Guard = (props: IGuardProps) =&gt; {\nconst hasRole = (requiredRole: string[]): boolean =&gt; {\nlet found: string | undefined = requiredRole.find(s =&gt; currentUser.role === s);\nreturn found !== undefined;\n}\n\nif (hasRole(props.requiredRoles)) {\n    return (\n        &lt;&gt;\n            {props.children}\n        &lt;\/&gt;\n    );\n} else {\n    return &lt;&gt;&lt;\/&gt;;\n}\n}\n\u201c`<\/code><\/pre>\n\n\n\n<p>And I could say stop here, but it will be too easy. Now we have component, and we can use it to the extreme \ud83d\ude00<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">`GuardService`<\/h3>\n\n\n\n<p>First step will be externalization of checks. <code>currentUser<\/code> is hardcoded value. I would like to encapsulate this value<br>into some service, that will \u201eknow\u201d how to verify roles. Technically that means we move <code>hasRole<\/code> function to another<br>class.<\/p>\n\n\n\n<p>I create simple interface <code>IGuardService<\/code> that has only one property \u2013 <code>hasRole<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">export interface IGuardService {\ncheckRole: (roles: string[]) =&gt; boolean;\n}<\/code><\/pre>\n\n\n\n<p>Now simple implementation could look like this<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">class SimpleGuard implements IGuardService {\ncheckRole(roles: string[]): boolean {\nlet found: string | undefined = roles.find(e =&gt; e === currentUser.role);\nreturn found !== undefined;\n}\n}<\/code><\/pre>\n\n\n\n<p>To use it we need to change <code>IGuardProperties<\/code> and use case.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">export interface IGuardProps extends React.PropsWithChildren {\nrequiredRoles: string[];\nguardService: IGuardService;\n}\n\n\/\/ \u2026\n\nconst AppHeader: FC = () =&gt; {\nconst guardService = new SimpleGuard();\nreturn (\n\nAdmin only component\n&nbsp;\n\nUser only component\n\nAdmin and User component\n&nbsp;\n&nbsp;\n\nGeneral usage element\n\n&nbsp;\n\n);\n}\n```<\/code><\/pre>\n\n\n\n<p>Now component looks like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\"><code> export const Guard = (props: IGuardProps) =&gt; {\n     if (props.guardService.checkRole(props.requiredRoles)) {\n         return (\n             &lt;&gt;\n                 {props.children}\n             &lt;\/&gt;\n         );\n     } else {\n         return &lt;&gt;&lt;\/&gt;;\n     }\n }\n <\/code><\/code><\/pre>\n\n\n\n<p>Much better. <code>GuardService<\/code> separate us from logic that check roles. We can change it without consequences for our<br>component. Common use case is to use mock in tests and some \u201ereal\u201d implementation in production code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Forbidden element<\/h3>\n\n\n\n<p>Next improvement will be handling custom <code>Forbidden<\/code> element. Current solution renders empty element. First we need to<br>change <code>IGuardProps<\/code> adding function that will be rendered that element.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\"><code> export interface IGuardProps extends React.PropsWithChildren {\n     requiredRoles: string[];\n     guardService: IGuardService;\n     forbidden?: () =&gt; React.ReactNode;\n }<\/code><\/code><\/pre>\n\n\n\n<p>This is optional property, name ends with question mark character. So it could be function or <code>undefined<\/code>. We need to<br>handle it in <code>Guard<\/code> component.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">export const Guard = (props: IGuardProps) =&gt; {\nif (props.guardService.checkRole(props.requiredRoles)) {\nreturn (\n&lt;&gt;\n{props.children}\n&lt;\/&gt;\n);\n} else if (props.forbidden === undefined) {\nreturn &lt;&gt;&lt;\/&gt;;\n} else {\nreturn (&lt;&gt;\n{props.forbidden()}\n&lt;\/&gt;\n);\n}\n}\n\n\/\/ \u2026\n\nexport const AppHeader: FC = () =&gt; {\nconst guardService = new SimpleGuard();\nreturn (\n\nAdmin only component\n&nbsp;\n\nUser only component\n\nForbidden \u2013 only moderator can see this\n}&gt;\n&nbsp;\n\nModerator component\n\n&nbsp;\n\nAdmin and User component\n&nbsp;\n&nbsp;\n\nGeneral usage element\n\n&nbsp;\n\n);\n}\n```<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Flexibility of types<\/h3>\n\n\n\n<p>Time to last big change. Current version component supports only roles as <code>string<\/code>. We could have multiple different<br>types of property that we would like to check. Numbers or custom types is nothing special. I will add generics support.<\/p>\n\n\n\n<p>First step is changes in <code>IGuardService<\/code> interface. Implementations will be depended on type of tested value. It could<br>be anything, so interface should handle it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\"><code> export interface IGuardService&lt;ROLE&gt; {\n     checkRole: (roles: ROLE[]) =&gt; boolean;\n }<\/code><\/code><\/pre>\n\n\n\n<p>Now it takes array of <code>ROLE<\/code> generic type. Our simple implementation will change a little.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\"><code> class SimpleGuard implements IGuardService&lt;string&gt; {\n     checkRole(roles: string[]): boolean {\n         let found: string | undefined = roles.find(e =&gt; e === currentUser.role);\n         return found !== undefined;\n     }\n }<\/code><\/code><\/pre>\n\n\n\n<p>We need to add type parameter, but we could prepare implementation that supports <code>IRole<\/code> interface.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">interface IRole {\nname: string;\n}\n\n\/\/\u2026\nclass RoleGuardService implements IGuardService {\ncheckRole(roles: IRole[]): boolean {\nlet found: IRole | undefined = roles.find(e =&gt; e === userWithRole.role);\nreturn found !== undefined;\n}\n}\n```<\/code><\/pre>\n\n\n\n<p>Second step is to propagate this change to <code>IGuardProps<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\"><code> interface IGuardProps&lt;ROLE&gt; extends React.PropsWithChildren {\n     requiredRoles: ROLE[];\n     guardService: IGuardService&lt;ROLE&gt;;\n     forbidden?: () =&gt; React.ReactNode;\n }<\/code><\/code><\/pre>\n\n\n\n<p>And respectively to <code>Guard<\/code> component.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">export const Guard = &lt;S, &gt;(props: IGuardProps&lt;S&gt;) =&gt; {\n     if (props.guardService.checkRole(props.requiredRoles)) {\n         return (\n             &lt;&gt;\n                 {props.children}\n             &lt;\/&gt;\n         );\n     } else if (props.forbidden === undefined) {\n         return &lt;&gt;&lt;\/&gt;;\n     } else {\n         return (&lt;&gt;\n                 {props.forbidden()}\n             &lt;\/&gt;\n         );\n     }\n }<\/code><\/pre>\n\n\n\n<p>And our use cases<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">export const AppHeader: FC = () =&gt; {\n     const guardService = new SimpleGuard();\n     const roleService = new RoleGuardService();\n     return (\n         &lt;header&gt;\n             &lt;nav&gt;\n                 &lt;ul&gt;\n                     &lt;Guard&lt;IRole&gt; requiredRoles={[{name: \"ADMIN\"}]} guardService={roleService}&gt;\n                         &lt;li&gt;Admin only component&lt;\/li&gt;\n                     &lt;\/Guard&gt;\n                     &lt;Guard&lt;string&gt; requiredRoles={[\"USER\"]} guardService={guardService}&gt;\n                         &lt;li&gt;User only component&lt;\/li&gt;\n                     &lt;\/Guard&gt;\n                     &lt;Guard&lt;string&gt; requiredRoles={[\"MODERATOR\"]} guardService={guardService}\n                                    forbidden={() =&gt; &lt;div&gt;Forbidden \u2013 only moderator can see this&lt;\/div&gt;}&gt;\n                         &lt;li&gt;Moderator component&lt;\/li&gt;\n                     &lt;\/Guard&gt;\n                     &lt;Guard&lt;string&gt; requiredRoles={[\"USER\", \"ADMIN\"]} guardService={guardService}&gt;\n                         &lt;li&gt;Admin and User component&lt;\/li&gt;\n                     &lt;\/Guard&gt;\n                     &lt;li&gt;General usage element&lt;\/li&gt;\n                 &lt;\/ul&gt;\n             &lt;\/nav&gt;\n         &lt;\/header&gt;\n     );\n }<\/code><\/pre>\n\n\n\n<p>In this example I use both implementation of <code>IGuardservice<\/code> just for illustrative purposes. In real use cases you<br>probably use only one.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Specialized components and nesting<\/h3>\n\n\n\n<p>The <code>Guard<\/code> could be nested. Just remember that access will be resolved in order from most external instance.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">export const NestAppHeader: FC = () =&gt; {\n     const guardService = new SimpleGuard();\n     return (\n         &lt;header&gt;\n             &lt;nav&gt;\n                 &lt;ul&gt;\n                     &lt;Guard&lt;string&gt; requiredRoles={[\"USER\", \"ADMIN\"]} guardService={guardService}&gt;\n                         &lt;Guard&lt;string&gt; requiredRoles={[\"ADMIN\"]} guardService={guardService}&gt;\n                             &lt;li&gt;Admin only component&lt;\/li&gt;\n                         &lt;\/Guard&gt;\n                         &lt;Guard&lt;string&gt; requiredRoles={[\"USER\"]} guardService={guardService}&gt;\n                             &lt;li&gt;User only component&lt;\/li&gt;\n                         &lt;\/Guard&gt;\n                         &lt;li&gt;Admin and User component&lt;\/li&gt;\n                         &lt;Guard&lt;string&gt; requiredRoles={[\"MODERATOR\"]} guardService={guardService}\n                                        forbidden={() =&gt; &lt;div&gt;Forbidden \u2013 only moderator can see this&lt;\/div&gt;}&gt;\n                             &lt;li&gt;Moderator component&lt;\/li&gt;\n                         &lt;\/Guard&gt;\n                     &lt;\/Guard&gt;\n                     &lt;li&gt;General usage element&lt;\/li&gt;\n                 &lt;\/ul&gt;\n             &lt;\/nav&gt;\n         &lt;\/header&gt;\n     );\n }<\/code><\/pre>\n\n\n\n<p>In above example <code>Moderator component<\/code> could never appear, because user can handle only one role. First <code>Guard<\/code> limits<br>roles to <code>ADMIN<\/code> and <code>USER<\/code>, so <code>MODERATOR<\/code> will never pass first check.<\/p>\n\n\n\n<p>We can build specialized components that hide some properties.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"typescript\" class=\"language-typescript\">export const AdminGuard = (props: Omit&lt;IGuardProps, \"requiredRoles\"&gt;) =&gt; {\nreturn &lt;Guard requiredRoles={[\"ADMIN\"]} guardService={props.guardService} forbidden={props.forbidden}&gt;\n{props.children}\n\n}\n\n\/\/\u2026\nexport const SpecializedAppHeader: FC = () =&gt; {\nconst guardService = new SimpleGuard();\nreturn (\n\nAdmin only component\n&nbsp;\n\n&lt;Guard requiredRoles={[\"USER\"]} guardService={guardService}&gt;\nUser only component\n\n&lt;Guard requiredRoles={[\"MODERATOR\"]} guardService={guardService}\nforbidden={() =&gt;\nForbidden \u2013 only moderator can see this\n}&gt;\n\nModerator component\n\n&lt;Guard requiredRoles={[\"USER\", \"ADMIN\"]} guardService={guardService}&gt;\n\nAdmin and User component\n\n&nbsp;\n\nGeneral usage element\n\n);\n}\n```<\/code><\/pre>\n\n\n\n<p>In this case <code>AdminGuard<\/code> predefine <code>ADMIN<\/code> role. In consequences, we need to explicit define type of <code>ROLE<\/code> type<br>parameter.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Sum up<\/h2>\n\n\n\n<p>In this article I show you how to create and use <code>Guard<\/code> <strong>component in React<\/strong>. We start from complex code that is hard to<br>read and maintain. We evolve it into more <a href=\"https:\/\/thecodest.co\/fr\/blog\/hire-vue-js-developers\/\">developer<\/a> friendly state and introduce custom functional component. Next we<br>extend component adding extra functionalities, refactor extracting service and finally add generics types.<\/p>\n\n\n\n<p>Finally, we have have component that could be nested is easy to test and maintain.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/thecodest.co\/contact\/\"><img loading=\"lazy\" decoding=\"async\" width=\"1283\" height=\"460\" src=\"https:\/\/thecodest.co\/app\/uploads\/2024\/05\/interested_in_cooperation_.png\" alt=\"\" class=\"wp-image-4927\" srcset=\"https:\/\/thecodest.co\/app\/uploads\/2024\/05\/interested_in_cooperation_.png 1283w, https:\/\/thecodest.co\/app\/uploads\/2024\/05\/interested_in_cooperation_-300x108.png 300w, https:\/\/thecodest.co\/app\/uploads\/2024\/05\/interested_in_cooperation_-1024x367.png 1024w, https:\/\/thecodest.co\/app\/uploads\/2024\/05\/interested_in_cooperation_-768x275.png 768w, https:\/\/thecodest.co\/app\/uploads\/2024\/05\/interested_in_cooperation_-18x6.png 18w, https:\/\/thecodest.co\/app\/uploads\/2024\/05\/interested_in_cooperation_-67x24.png 67w\" sizes=\"auto, (max-width: 1283px) 100vw, 1283px\" \/><\/a><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>D\u00e9couvrez comment simplifier et am\u00e9liorer la visibilit\u00e9 des composants dans React \u00e0 l'aide du rendu conditionnel et des composants de garde.<\/p>","protected":false},"author":2,"featured_media":3141,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"footnotes":""},"categories":[8],"tags":[],"class_list":["post-3140","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-software-development"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.3 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Component Visibility in React with Conditional Rendering and Guards - The Codest<\/title>\n<meta name=\"description\" content=\"Learn how to simplify and improve component visibility in React using conditional rendering and guard components.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/thecodest.co\/fr\/blog\/visibilite-conditionnelle-des-composants-dans-react\/\" \/>\n<meta property=\"og:locale\" content=\"fr_FR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Component Visibility in React with Conditional Rendering and Guards\" \/>\n<meta property=\"og:description\" content=\"Learn how to simplify and improve component visibility in React using conditional rendering and guard components.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/thecodest.co\/fr\/blog\/visibilite-conditionnelle-des-composants-dans-react\/\" \/>\n<meta property=\"og:site_name\" content=\"The Codest\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-19T06:28:57+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-03-05T10:47:23+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/thecodest.co\/app\/uploads\/2024\/05\/conditional-component-visibility-in-react.png\" \/>\n\t<meta property=\"og:image:width\" content=\"960\" \/>\n\t<meta property=\"og:image:height\" content=\"540\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"thecodest\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"thecodest\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/\"},\"author\":{\"name\":\"thecodest\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/#\\\/schema\\\/person\\\/7e3fe41dfa4f4e41a7baad4c6e0d4f76\"},\"headline\":\"Component Visibility in React with Conditional Rendering and Guards\",\"datePublished\":\"2023-05-19T06:28:57+00:00\",\"dateModified\":\"2026-03-05T10:47:23+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/\"},\"wordCount\":877,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/thecodest.co\\\/app\\\/uploads\\\/2024\\\/05\\\/conditional-component-visibility-in-react.png\",\"articleSection\":[\"Software Development\"],\"inLanguage\":\"fr-FR\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/\",\"url\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/\",\"name\":\"Component Visibility in React with Conditional Rendering and Guards - The Codest\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/thecodest.co\\\/app\\\/uploads\\\/2024\\\/05\\\/conditional-component-visibility-in-react.png\",\"datePublished\":\"2023-05-19T06:28:57+00:00\",\"dateModified\":\"2026-03-05T10:47:23+00:00\",\"description\":\"Learn how to simplify and improve component visibility in React using conditional rendering and guard components.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/#breadcrumb\"},\"inLanguage\":\"fr-FR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"fr-FR\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/#primaryimage\",\"url\":\"https:\\\/\\\/thecodest.co\\\/app\\\/uploads\\\/2024\\\/05\\\/conditional-component-visibility-in-react.png\",\"contentUrl\":\"https:\\\/\\\/thecodest.co\\\/app\\\/uploads\\\/2024\\\/05\\\/conditional-component-visibility-in-react.png\",\"width\":960,\"height\":540},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/blog\\\/conditional-component-visibility-in-react\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/thecodest.co\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Component Visibility in React with Conditional Rendering and Guards\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/#website\",\"url\":\"https:\\\/\\\/thecodest.co\\\/\",\"name\":\"The Codest\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/thecodest.co\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"fr-FR\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/#organization\",\"name\":\"The Codest\",\"url\":\"https:\\\/\\\/thecodest.co\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"fr-FR\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/thecodest.co\\\/app\\\/uploads\\\/2024\\\/03\\\/thecodest-logo.svg\",\"contentUrl\":\"https:\\\/\\\/thecodest.co\\\/app\\\/uploads\\\/2024\\\/03\\\/thecodest-logo.svg\",\"width\":144,\"height\":36,\"caption\":\"The Codest\"},\"image\":{\"@id\":\"https:\\\/\\\/thecodest.co\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/pl.linkedin.com\\\/company\\\/codest\",\"https:\\\/\\\/clutch.co\\\/profile\\\/codest\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/thecodest.co\\\/#\\\/schema\\\/person\\\/7e3fe41dfa4f4e41a7baad4c6e0d4f76\",\"name\":\"thecodest\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"fr-FR\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5dbfe6a1e8c86e432e8812759e34e6fe82ebac75119ae3237a6c1311fa19caf4?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5dbfe6a1e8c86e432e8812759e34e6fe82ebac75119ae3237a6c1311fa19caf4?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5dbfe6a1e8c86e432e8812759e34e6fe82ebac75119ae3237a6c1311fa19caf4?s=96&d=mm&r=g\",\"caption\":\"thecodest\"},\"url\":\"https:\\\/\\\/thecodest.co\\\/fr\\\/author\\\/thecodest\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Visibilit\u00e9 des composants dans React avec rendu conditionnel et protections - The Codest","description":"D\u00e9couvrez comment simplifier et am\u00e9liorer la visibilit\u00e9 des composants dans React \u00e0 l'aide du rendu conditionnel et des composants de garde.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/thecodest.co\/fr\/blog\/visibilite-conditionnelle-des-composants-dans-react\/","og_locale":"fr_FR","og_type":"article","og_title":"Component Visibility in React with Conditional Rendering and Guards","og_description":"Learn how to simplify and improve component visibility in React using conditional rendering and guard components.","og_url":"https:\/\/thecodest.co\/fr\/blog\/visibilite-conditionnelle-des-composants-dans-react\/","og_site_name":"The Codest","article_published_time":"2023-05-19T06:28:57+00:00","article_modified_time":"2026-03-05T10:47:23+00:00","og_image":[{"width":960,"height":540,"url":"https:\/\/thecodest.co\/app\/uploads\/2024\/05\/conditional-component-visibility-in-react.png","type":"image\/png"}],"author":"thecodest","twitter_card":"summary_large_image","twitter_misc":{"Written by":"thecodest","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/#article","isPartOf":{"@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/"},"author":{"name":"thecodest","@id":"https:\/\/thecodest.co\/#\/schema\/person\/7e3fe41dfa4f4e41a7baad4c6e0d4f76"},"headline":"Component Visibility in React with Conditional Rendering and Guards","datePublished":"2023-05-19T06:28:57+00:00","dateModified":"2026-03-05T10:47:23+00:00","mainEntityOfPage":{"@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/"},"wordCount":877,"commentCount":0,"publisher":{"@id":"https:\/\/thecodest.co\/#organization"},"image":{"@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/#primaryimage"},"thumbnailUrl":"https:\/\/thecodest.co\/app\/uploads\/2024\/05\/conditional-component-visibility-in-react.png","articleSection":["Software Development"],"inLanguage":"fr-FR","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/","url":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/","name":"Visibilit\u00e9 des composants dans React avec rendu conditionnel et protections - The Codest","isPartOf":{"@id":"https:\/\/thecodest.co\/#website"},"primaryImageOfPage":{"@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/#primaryimage"},"image":{"@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/#primaryimage"},"thumbnailUrl":"https:\/\/thecodest.co\/app\/uploads\/2024\/05\/conditional-component-visibility-in-react.png","datePublished":"2023-05-19T06:28:57+00:00","dateModified":"2026-03-05T10:47:23+00:00","description":"D\u00e9couvrez comment simplifier et am\u00e9liorer la visibilit\u00e9 des composants dans React \u00e0 l'aide du rendu conditionnel et des composants de garde.","breadcrumb":{"@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/#breadcrumb"},"inLanguage":"fr-FR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/"]}]},{"@type":"ImageObject","inLanguage":"fr-FR","@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/#primaryimage","url":"https:\/\/thecodest.co\/app\/uploads\/2024\/05\/conditional-component-visibility-in-react.png","contentUrl":"https:\/\/thecodest.co\/app\/uploads\/2024\/05\/conditional-component-visibility-in-react.png","width":960,"height":540},{"@type":"BreadcrumbList","@id":"https:\/\/thecodest.co\/blog\/conditional-component-visibility-in-react\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/thecodest.co\/"},{"@type":"ListItem","position":2,"name":"Component Visibility in React with Conditional Rendering and Guards"}]},{"@type":"WebSite","@id":"https:\/\/thecodest.co\/#website","url":"https:\/\/thecodest.co\/","name":"The Codest","description":"","publisher":{"@id":"https:\/\/thecodest.co\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/thecodest.co\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"fr-FR"},{"@type":"Organization","@id":"https:\/\/thecodest.co\/#organization","name":"The Codest","url":"https:\/\/thecodest.co\/","logo":{"@type":"ImageObject","inLanguage":"fr-FR","@id":"https:\/\/thecodest.co\/#\/schema\/logo\/image\/","url":"https:\/\/thecodest.co\/app\/uploads\/2024\/03\/thecodest-logo.svg","contentUrl":"https:\/\/thecodest.co\/app\/uploads\/2024\/03\/thecodest-logo.svg","width":144,"height":36,"caption":"The Codest"},"image":{"@id":"https:\/\/thecodest.co\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/pl.linkedin.com\/company\/codest","https:\/\/clutch.co\/profile\/codest"]},{"@type":"Person","@id":"https:\/\/thecodest.co\/#\/schema\/person\/7e3fe41dfa4f4e41a7baad4c6e0d4f76","name":"thecodest","image":{"@type":"ImageObject","inLanguage":"fr-FR","@id":"https:\/\/secure.gravatar.com\/avatar\/5dbfe6a1e8c86e432e8812759e34e6fe82ebac75119ae3237a6c1311fa19caf4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/5dbfe6a1e8c86e432e8812759e34e6fe82ebac75119ae3237a6c1311fa19caf4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/5dbfe6a1e8c86e432e8812759e34e6fe82ebac75119ae3237a6c1311fa19caf4?s=96&d=mm&r=g","caption":"thecodest"},"url":"https:\/\/thecodest.co\/fr\/author\/thecodest\/"}]}},"_links":{"self":[{"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/posts\/3140","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/comments?post=3140"}],"version-history":[{"count":22,"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/posts\/3140\/revisions"}],"predecessor-version":[{"id":8548,"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/posts\/3140\/revisions\/8548"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/media\/3141"}],"wp:attachment":[{"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/media?parent=3140"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/categories?post=3140"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thecodest.co\/fr\/wp-json\/wp\/v2\/tags?post=3140"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}