Tips for utilizing the onClick handler when mapping through items in React

Currently, I am a student learning about react. During the course of working on a project, I encountered a problem that left me with a question.

{pages.map((page, idx) => (
  <li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}>
    <Photo onClick={() => console.log('click!')}/>
    <p css={CSSPageContent}>{page.text}</p>
........
  </li>
))}

and Photo components

interface PhotoProps {
.....
  onClick?: () => void;
}


const Photo = ({ src, width, height, blur, custom, onClick, text, placeholder }: PhotoProps) => {
  return (
    <div
      onClick={onClick}>
    ... 
    </div>

I find myself in a situation where I need to implement an onClick handler specifically for the Photo components.However, due to the nature of how the mapping is set up, the onClick is only being applied to the highest element (li components) and not triggering the desired behavior for the Photo component's onClick function. Is there any way around this limitation?

Thank you for taking the time to read through my query.

Answer №1

Avoid attaching the onClick handler directly to the mapped element. Instead, apply it to the specific component within the mapped element. Simply pass the onClick handler to the Photo component inside the li element like this:

{pages.map((page, idx) => (
  <li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}>
    <Photo onClick={() => { /* your onClick handler here */ }} />
    <p css={CSSPageContent}>{page.text}</p>
........
  </li>
))}

By doing so, the onClick handler will be applied to the specific component and can be triggered when the Photo component is clicked on its parent component.

Answer №2

Integrate an onClick function as a prop in the Photo component.

{pages.map((page, idx) => (
  <li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}>
    <Photo onClick=(() => {/* implement your click function here */})/>
    <p css={CSSPageContent}>{page.text}</p>
........
  </li>
))}

Include the necessary attribute for your image (or relevant element).

function Photo({onClick}) {
   <img onClick={onClick}/>
}

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

NextJS component fails to re-render after being updated

I've been diving into the world of useEffect, useState, and rerendering, but I'm struggling to grasp the core issue at hand. While the data update itself is functioning properly, I find myself needing to manually refresh the page in order to see ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Automatically navigate to the AAD login page when the URL is entered into the browser

If you're using MSAL 2.0 in React, achieving a redirect to the login page can be done through various methods: Logging in with a pop-up Logging in with a redirect However, these methods are typically triggered by a login or sign-in button click. In ...

Shallow routing in Next/Link allows for the refreshing of the page when a

My inquiry pertains to the usage of a Link: <Link href={href} passHref shallow> <StyledLink $active={active} $disabled={disabled} onClick={() => passBackNumber(number)} > {number} </Styled ...

Dealing with the "empty_url_error" while configuring a Next.js project with Microsoft Azure AD

I've been working on setting up Microsoft Azure AD authentication, and I believe I have filled in all the required fields correctly. However, despite my efforts to avoid sharing any confidential information, I keep encountering an "empty_url_error" me ...

Issue with resolving the '@/theme' module while using Material UI with Nextjs

As a newcomer to MUI, I am facing an issue with the material-ui-nextjs app router example. After setting up the project, I encountered an error when trying to import the theme module - "Module not found: Can't resolve '@/theme'". Below are s ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Create a combined string from a structure resembling a tree

In my web application, I have a type that defines the different routes available: interface IRoute { readonly path: string, readonly children?: IRoute[] } I want to create a union type containing all possible paths based on an IRoute object. Let&apos ...

The module './product' could not be located, resulting in error TS2307

app/product-detail.component.ts(2,22): error TS2307: Cannot find module './product'. I have tried several solutions but none of them seem to work for me. I am working on a demo app in Angular 2 and encountering this specific error. Any guidance ...

The HTML canvas drawImage method overlays images when the source is modified

Trying to implement a scroll animation on my website, I came across a guide for creating an "Apple-like animation" using image sequences. Even though I'm new to Angular, I attempted to adapt the code to work with Angular. However, instead of animatin ...

Cannot read property 'focusVisible' of null error is occurring on the radio

Having a complex setup involving Gatsby 1.9, react-next, React 16.5.2, and Material UI 3.2.2. Encountering issues with Radio and RadioGroup components consistently causing a strange error to pop up (refer to the image below). Unfortunately, unable to upg ...

Searching for data based on specific keywords in Angular 2, rather than using a wildcard search, can be done by utilizing the key-in

My dropdown contains 100 values, and I am currently able to search for these values based on key input using wild search. However, I would like the dropdown to display values based on the specific alphabet that I enter first. HTML: <div class="col- ...

Utilizing a setup module for configuration purposes

In the process of developing my angular application, I have integrated several external modules to enhance its functionality. One crucial aspect of my final application is the configuration classes that store important values like URLs and message keys us ...

Sonar activated - Self-hosted runner limitation: unable to use npm for test coverage alongside Docker integration

Whenever I attempt to execute the (action checkout) on a self-hosted runner with npm run coverage and then after sonarqube, I encounter this error:" docker: Error response from daemon: pull access denied for 6cd1db, repository does not exist or may re ...

Having trouble getting Persistent Drawer to function properly with material-ui v5

Currently experimenting with the Persistent Drawer example from the official documentation here, but encountering issues during compilation. /Users/alex/Dev/wnav-react2/src/App.tsx TypeScript error in /Users/alex/Dev/wnav-react2/src/App.tsx(24,15): Propert ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

What is the best way to transfer data received from an observable function to use as an input for another observable function?

After carefully declaring all the variables, I am facing an issue with passing the value obtained from the first observable function (this.acNum) as a parameter to resolve the second observable function within the ngOnInit method. Despite displaying correc ...

What is the process for converting an image into base 64 using Angular 5?

Is there a way to convert an image into base 64 using angular5 when the image is sourced from Facebook or Google authentication API? I seem to be encountering an issue, what could I be doing wrong? getBase64Image(img) { var canvas = document.createEleme ...

Preventing NextJS Link Component from Displaying 404 Error

Hey there, can anyone help me figure out why my Link Component is having trouble finding the linked page? It's weird because VSCode is auto-completing the file name as I type it in, but all I get is a 404 error. //index.js in WelcomePage folder import ...

"Despite using the setHeader function in express.js to set a cookie, an empty cookie is still being

customer: <a href="http://localhost:3001/user/login">Login</a> server: const token = jwt.sign({ broadcasterId: user.twitchId }, process.env.JWT_SECRET); res.writeHead(301, { "Location": "http://localhost:3000" ...