Toggle the highlighting in React

I have a list of data that displays in a Collapse, and I want it to highlight for every user click in the list, but only one at a time should be highlighted.

If you'd like to see a sample to better understand this concept, please check out:

https://example.com/sample

const [highlight, setHighlight] = useState(false)
const handleClick = () => {
   if (on) set(null)
   else set(index)
}
  <Collapse in={viewLocationList} sx={{ my: '2px' }}>
    {!!searchParameter && (
      <Box className="rounded-scrollbar widget-result-container"
      onClick={handleClick}
      sx={{
        my: 1,
        bgcolor: on && "lightgrey",
        "&:hover": { bgcolor: on && "lightgrey" }
      }}
      >
        {filteredLocations.map((location, key, on) => (
          <LocationWidgetItem
            key={key}
            location={location}
            onClickLocation={setActiveLocation}
            index={key} on={highlight === key} set={setHighlight}
          />
        ))}
      </Box>
    )}
  </Collapse>

Please note the error in the current code:

Answer №1

Chances are, you may have forgotten to pass the "on" prop from the parent component to your item component, similar to the example provided.

Answer №2

Your sandbox has been set up correctly. The issue lies in the fact that you are attempting to pass an on prop from your filteredLocations map, which does not actually exist. This prop is not necessary because you already define the on with the highlight === key comparison later on.

Instead of:

{filteredLocations.map((location, key, on) => (...)}

try rendering your list like this:

{filteredLocations.map((location, key) => (...)}

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

Looking for a list that you can edit with CSS styling?

I'm struggling to create a flexible list that can be easily modified. My goal is to have an ordered list with unique labels such as 1,2,3,4,5,6,7,8,9,0,A,B,!,# Although I've managed to number the list items, I am stuck on adding the extra label ...

The MUI icon is visible in the developer tools but fails to display on the screen

Recently, I've been troubleshooting MUI icons in React and encountered an issue where my icons weren't displaying properly even after npm installing @mui/icons-material and importing them using the code snippet below: import HomeIcon from "@mui/i ...

The exterior DIV does not conform to shrinking dimensions

I've set the display property to inline-block, but the htmlDiv div in this code snippet is not behaving as expected. It's acting as though the inner divs are next to each other even when they're not. How can I fix this? If it's unclear ...

When the SVG icon is clicked, it will redirect to a different page

I'm trying to figure out how to add a href attribute to an SVG icon in order to redirect to another page when the icon is clicked. I've saved the SVG icon as a React Component, but I'm unsure of what steps to take next. import React from &ap ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

Combining two numbers retrieved from Firebase using React

Hello, I am new to React and finding it challenging to perform mathematical calculations with React. I have been attempting to add two values retrieved from a Firebase database, but they keep displaying as strings without adding the actual values together. ...

Ways to add a string to an array as a labeled object in javascript?

Is there a way to manipulate the array in imageCollection to achieve the format of the array in carouselPhotos as shown below? export default class HomeScreen extends Component { state = { imageCollection: [ { name: "P ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

The 'posts' binding element is assumed to have a type of 'any' by default

Currently, I'm working on a code project that involves graphql, react, and typescript. In the middle of the process, I encountered an error message stating "Binding element 'posts' implicitly has an 'any' type." I am unsure about w ...

The problem with -webkit-center in HTML

I have encountered an issue with some code that I wrote. When utilizing -webkit-center and entering text into a textbox, all the items shift to the right. I have attempted other -webkit alignment settings without any problems, only -webkit-center seems to ...

Hacking your way through the MenuItem navigation in material-ui V1

How can a MenuItem be used for navigation to another route? For example, when a menu item is clicked, the desired route is '/account' I have been able to achieve this using an onclick function, but I believe there must be a simpler way. Please ...

choose a selection hopscotch

Is there a way to prevent the input field from jumping out of alignment when an option is selected in these q-select inputs? I want to fix this issue so that the field remains in line with the horizontal alignment. https://codepen.io/kiggs1881/pen/RwENYEX ...

`Considering various factors to alter class pairings`

I have defined a few style classes in my stylesheet as shown below: .left-align{ /* some styles here */ } .right-align{ /* some styles here */ } .validate-error{ /* some styles here */ } Depending on the type of data, I need to align the content ei ...

Utilizing ASCII art in React: A guide to incorporating textual designs into your

I'm having trouble displaying ASCII images correctly on my React app. I've tried various methods, but nothing seems to maintain the form when rendered in the browser. <Grid container id="terminal_banner"> <Grid item ...

Enhance your website's performance with Next.js by utilizing codesplitting for conditional

As someone new to Next.js, I have a question. I'm interested in creating a back-end/admin area for existing pages. My plan is to set up an authentication wrapper inside _app.js that will always check for an auth token in local storage. If no token is ...

Is it possible to apply a background image on top of an existing image?

Is it possible to set a background image on an img tag? This is my current HTML markup: <div id="content"> <img src="my-image.jpg" alt="image" class="img-shadow"> </div> Here is my CSS code: #content img { floa ...

I am trying to display my progress bar in a col-sm-6 format on screens larger than 546px, however, despite my attempts, I am not seeing any changes on the screen

Is there an alternative method if bootstrap is unable to handle this? I have used col-xs-6, but all I want is to display my progress bar in the image shown on small screens. Here is how I want to display my image on small screens. <div class="cont ...

Missing Bootstrap 3 Options Menu trip away

I created a table with 4 columns using the Bootstrap 3 grid system. Instead of utilizing the col-xs-* classes, which work well on mobile devices, I opted for the col-md-* classes. This decision was based on my preference to have larger and more visible ico ...

Disabling Sidebars on Blog Articles Exclusively for Mobile Devices

I own the website Onthecomeupartists.com and am currently using the Impreza Theme 2.10 on WordPress 4.5.2. However, I want to enhance the mobile compatibility of my site by removing the sidebar on blog posts when viewed on mobile devices only, while keepin ...