Implementing conditional rendering with styled-components

Currently, I am working on a menu that consists of a list of MenuItem components:

          <MenuItem>A</MenuItem>
          <MenuItem>B</MenuItem>
          <MenuItem>C</MenuItem>

I am looking to customize the component to be visible only when a boolean (such as `isLoggedIn`) is true. Is there a way to achieve this without manually adding a condition to each of the menu items, especially since I have a large number of them?

const PrivateMenuItem = styled.MenuItem` \\what to write here `;

          <PrivateMenuItem>A</PrivateMenuItem>
          <PrivateMenuItem>B</PrivateMenuItem>
          <PrivateMenuItem>C</PrivateMenuItem>

Answer №1

One way to address this is by creating a component to handle it for you:

const CustomMenuItem = ({show=true, children}) => {
  return show ? <MenuItem>{children}</MenuItem> : null;
}

If you prefer to hide it using styling, you can modify the component like this:

const CustomMenuItem = ({show=true, children}) => {
  return show ? 
          <MenuItem className={styles.show}>{children}</MenuItem> :
          <MenuItem className={styles.hide}>{children}</MenuItem>;
}

Then, you can use it as follows:

<CustomMenuItem show={true}>A</CustomMenuItem>
<CustomMenuItem show={false}>B</CustomMenuItem>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting runtime environment variables for a React application

I have a React Application that needs to be deployed to Cloud Foundry and I am looking for a way to segregate the development, staging, and production environments. The challenge is that React only provides .env.development for running the application usin ...

Styling elements with CSS

I've been attempting to align a button to the right of another button. The example above illustrates what I'm trying to achieve. I used Bootstrap to build it, which has a useful navbar feature for layout. However, despite my efforts to use right ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

Ways to emphasize the current tab on the site's navigation bar?

Here's my question: I have a menu with different items, and I want to make sure that the active tab is highlighted when users switch to another page. I noticed that Stack Overflow uses the following CSS: .nav { float: left; font-size: 1 ...

Error: The function "utils.useControlled" was not caught as a TypeError

There was a problem encountered when trying to render the Autocomplete component from @material-ui/lab Here are the versions of material-ui being used: "@material-ui/core": "4.9.5", "@material-ui/lab": "4.0.0-alpha.45", ...

"Troubleshooting: Why isn't the nested array in UseState updating and rendering correctly within a JavaScript file in

Struggling to grasp the concept of "useState" and when a render is triggered in React. I'm working on implementing a drag and drop system where users can move elements between boxes. In my previous attempts using pure JavaScript, things quickly got m ...

Using Typescript to Declare Function and React Component Types

Currently challenging myself to delve into Typescript (ugh). Usually, I can deduce the appropriate type by analyzing the return values. Nonetheless, in this particular scenario, that method is proving ineffective. type SomeReactAProps = { Type1: ReactEle ...

Is it best practice to display a DIV once it is no longer visible after scrolling down?

Upon opening my website, an information box (div) appears on the screen. However, when the user scrolls down and the box is no longer visible, I want it to always appear in the top right corner while scrolling. I have figured out how to keep it visible at ...

"Customize your map pins on Google Maps by updating the marker location through a

I am trying to update the position of a map marker based on a dropdown selection. Upon changing the dropdown option, I retrieve the latitude and longitude values and want to set these coordinates for my current marker. Here is the code snippet: $("#locati ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

Error: Unable to locate image module in REACT

Trying to troubleshoot image loading in a React project. Currently testing with an individual image, but plan to eventually store multiple images in an array for easier management. However, I'm encountering an issue where the image won't load and ...

What is the best way to shift a link to the right within a "div" element?

I've been working on setting up a navigation menu for my website, and I'm having trouble getting the "quit" link to align to the right while keeping the other links aligned to the left. I've tried various methods but just can't seem to ...

Is there a way to sequentially load two iframes, with the second one loading only after the first one is fully loaded

Having two different links that trigger ajax calls can be tricky if only one request is allowed per load. This may result in both iframes displaying the same data. Is there a way to work around this issue? Perhaps loading one iframe first and then triggeri ...

How can I show the table row as an inner table row when the first field is identical?

<tr ng-model="check" ng-repeat="orderBook in orderBookDetails| orderBy: 'orderBook.no'" value='check=$scope.orderBookDetails.sowNo'> <td ng-if='check!=orderBook.no'>{{orderBook.no}}</td> <td>{{order ...

I'm encountering an issue with Firebase integration in my Next.js project

Encountered an error: Unable to locate module. The package path "." is not exported from the "/home/kapil/web/facebook-clone/node_modules/firebase" package (refer to the exports field in the "/home/kapil/web/facebook-clone/node_modules/firebase/package.jso ...

Implementing a transition effect to the drawimage function

I am currently working on implementing a transition effect for an image inside a canvas element. I have provided a snippet below to demonstrate my progress so far. Can anyone guide me on how to incorporate a transition animation for the image within the c ...

Encountering issue when deploying multiple HTML files using Parcel

Whenever I deploy a website with multiple entry points and many HTML files, and the host uses the build command: parcel build index.html aboutme.html, the deployed website gives me a 404 error. However, if I manually enter /aboutme.html or /index.html in t ...

Difficulty encountered in setting the width of a sticky bottom element to be located at the bottom of the page with Tailwind

Fiddle: https://play.tailwindcss.com/pvT1jW8zZd Here is the code snippet I am working with: Here is how it currently appears: https://i.sstatic.net/2SRny.png <div class="bg-yellow-300"> <div class="p-16 m-5 text-xl bg-gray-500 ...

Showing hierarchical objects retrieved from JSON response

I'm still learning React, so bear with me if this is a simple issue. I have some nested data that I want to show in a list format. The data is fetched and displayed below: data: [ { "id": 1, "domain_url": "localhost", "created_on": "2020-05-26" ...

Encountering an error while attempting to import a module with an alias specified in the

I recently came across a helpful Stack Overflow post that I used as a guide to implement path aliases for importing modules. Here is a snippet from my package.json : { ... "imports": { "#components/*": "src/components/*&qu ...