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.

https://i.sstatic.net/eM3JY.png

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

Is there a way to obtain HTML code within a contentEditable DIV?

When working in a contentEditable-DIV, my goal is to extract the HTML code from the starting position (0) to the end position where the user has clicked. <div id="MyEditableId" contentEditable="true"> 1. Some text 123. <span style="background-c ...

Is there a way to alter the background image of the logo specifically for mobile device viewing?

Here is a snippet of my HTML code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="{{ route('home') }}"> <img src="{{ asset('assets/images/logo-school-icon.png') }}" ...

Using NextJS to navigate user journey by mapping an array of values from Formik to

I really appreciate all the help I've received so far, but I'm facing an issue trying to map an object with an array within it to the router. Here is my current code: const initialValues = { region: query.region || 'all', campt ...

Collect data from website submissions via email

Is it possible to receive the results via email when someone submits their details on my site using a script? My server does not allow .php or .asp files, only .css. How can I achieve this? ...

What steps can I take to make sure that a sub component's props are refreshed properly?

I'm encountering an issue with RTK queries in my project. I have a parent component that contains a table component. When a refresh event occurs, such as deleting data, the parent component receives updated data and passes it down to the child compone ...

Attempting to apply custom styles to jQuery components using CSS

Looking to restyle the black bar on my test page located at The black bar with 3 tabs about halfway down the page needs a new color scheme. By inspecting with FireBug, I found these elements: <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ...

Implementing Meteor authentication with a slightly separated JSON web service for storing data in postgresql

After delving into meteor with react to construct an IOS and android app, I must reflect on my journey through MS SQL, classic asp, and asp.net ten years ago. Since then, my knowledge has expanded to include nodeJS and a bit of react. The app I'm dev ...

Troubleshooting cross-origin resource sharing (CORS) issue with passport-azure-ad in a React

I'm currently working on a React + Express application where I've implemented the passport-azure-ad OIDCStrategy. However, I'm facing issues related to CORS. The specific error message that I'm encountering is: Access to XMLHttpRequest ...

There seems to be an issue with Material UI Autocomplete not responding to the onChange value

I am currently developing a project using reactjs and incorporating material ui to create components. One specific component I have utilized is the Autocomplete within a form for event creation in my project. I am encountering an issue where I want the sta ...

Solving the issue of "Property does not exist on type 'never'" in a program involves identifying the root cause of

Issue An error message related to .cropper is occurring with the code snippet below. Error Message The property 'cropper' does not exist on type 'never'. Query How can I resolve the error associated with type 'never'? B ...

Tips for centering elements in an image caption

I need some help with separating an image and text within an image caption from each other. Currently, they are overlapping and I want them to be distinct. I attempted using inner div elements for the text and image separately, but it caused issues by brea ...

Setting up the configuration for eslint and prettier in a create-react-app

I keep receiving these error messages: However, I do not encounter any errors in Visual Studio Code. This is the ESLint configuration that I am using: const path = require('path'); module.exports = { env: { browser: true, es2021: tru ...

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

CSS has inexplicably ceased to function properly, with the exception of the body

My roommate submitted his project, but only the CSS for the body tag and Bootstrap elements are working properly. When inspecting the webpage, I noticed that none of the CSS changes were showing up, even after editing the Sublime file (except for the body ...

What is the best way to implement an OR filter in the DevExtreme React Grid Table using either FilteringState, LocalFiltering, or a

According to a past issue #499 that is now closed on the devextreme-reactive github repository, I am interested in implementing compound filtering functionalities within the Grid/TableView components. Currently, there are two examples of filtering compone ...

Why should I set the width of the header to be larger than the body in order to fully cover it?

I've set my header width to 106% to span the entire page length, while the max-width for my body is kept at 95%. body { background-color: #333; max-width: 95%; font-family: ivyjournal, sans-serif; margin: 0; padding: 0; overflow-x: hidd ...

Challenges arising from CSS position: fixed on iPhone 6+ in landscape orientation running iOS 9

Encountered a strange issue with the fixed header on my website under specific conditions: Using an iPhone 6+ in landscape mode. Using Safari with at least two tabs opened. The page has a fixed position header with html and body set to position: relative ...

Perfectly Aligning Image at the Center of the Screen

I'm having trouble centering a loading image on my screen. It seems to be centered closer to the bottom rather than in the middle. Any suggestions on how I can adjust it to be more centered vertically? Edit: I also want it to look good on mobile devi ...

Can you explain the mechanics behind the animation of the upvote button on steemit.com?

Behold the upvote button of steemit.com: <span class="Icon chevron-up-circle" style="display: inline-block; width: 1.12rem; height: 1.12rem;"> <svg enable-background="new 0 0 33 33" version="1.1" viewBox="0 0 33 33" xml:space="preserve" xmlns=" ...

Can you show me a way to use jQuery to delete several href links using their IDs at once?

Currently facing a challenge with removing multiple href links that share the same ID. Here is a snippet of my code: $('.delblk').click(function(e) { e.preventDefault(); var id = $(this).attr('id').substr(7); ...