When invoking a function, a React Component utilizes the props from the first element instead of its own

Whenever I try to invoke a function of a component, it seems to be replacing the parameters and passing the props of the first array element instead of the selected one.

To illustrate this issue, let's take a look at some code:

Firstly, here is how I render my list of components:

const HomeSections = () => {
  const [state, setState] = useContext(AppContext)
  const { HomeSections: SectionData } = state.Something
  
  return (
    <aside>
      <div>
        {SectionData.map(({ title, description, imgUrl, identifier }) => {
          return (
            <Section
              title={title}
              description={description}
              imgUrl={imgUrl}
              key={identifier}
              id={identifier}
            />
          )
        })}
      </div>
    </aside>
  )
}

export default HomeSections;

This is the structure of my component:

const Section = ({ title, description, imgUrl, id }) => {
  const [state, setState] = useContext(AppContext)
  const { register, setValue } = useForm()
  setValue('title', title)
  setValue('description', description)

  const doSomething = (identifier) => {
    // The id is being overwritten by the first element in the array here
  }

  return (
    <div className="SomethingSection__Container">
      <input
        className="hidden"
        type="file"
        id="HomeSections__SectionSomething"
        onChange={() => doSomething(id)}
      />
    </div>
  )
}

Section.propTypes = {
  title: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
  imgUrl: PropTypes.string.isRequired,
}

export default Section;

Every time I select an element from the array (by clicking on the button), the parameter passed to the `doSomething()` function within the component is always the first element instead of the clicked one.

I understand that my code may be confusing, so any assistance would be greatly appreciated!

Thank you!

Answer №1

After some investigation, I came to the realization that each component was receiving the same input, causing the function doSomething to always target the first ID it finds. To solve this issue, I decided to assign a unique custom id to each input element. However, with better implementation, I could optimize the code to reference a single input for all components by binding the function differently.

return (
    <div className="SomethingSection__Container">
      <input
        className="hidden"
        type="file"
        id={`HomeSections__SectionSomething-${randomString}`}
        onChange={() => doSomething(id)}
      />
    </div>
  )
}

Answer №2

Section receives the ID prop, allowing all functions declared within Section to access the ID without requiring it as an argument.

The issue may be due to an excess of arrow functions. This can lead to a reference problem where executed code contains outdated data.

const performAction = () => {
    console.log(id)
  }

...

onChange={performAction}

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

I am having trouble getting the jsTree ajax demo to load

I am having trouble running the basic demo "ajax demo" below, as the file does not load and the loading icon continues to churn. // ajax demo $('#ajax').jstree({ 'core' : { 'data' : { ...

Tips for preserving user input from HTML into a text file and then reloading it back into the HTML document

I have recently created a character sheet for a game using HTML. The HTML file is mainly comprised of various input tags such as <input type="text">, <input type="number">, <input type="checkbox">, <input type="radio">, <select&g ...

Issues with Stripe Checkout Integration in Nextjs and Django Environment

Currently, I am working on creating a payment page in Next.js using Stripe. Following the guide works perfectly fine, but I am exploring an alternative approach. Instead of using a form to call the /create-checkout-session endpoint, I want to trigger this ...

What is the best way to showcase a user's input in a webpage using vanilla javascript

Struggling with creating functionalities for a simple calculator using vanilla.js. Able to display numbers on click but facing issues with multiple clicks and deletion of values. Trying to use addeventlistener but encountering a Type Error "addeventliste ...

cycle through several handlebars entities

Hey friends, I could really use your help right now. I'm attempting to iterate through these objects using handlebars. RowDataPacket { idUser: 1, username: 'xxxxxx', password: 'xxxxx', fullname: 'Julian Rincon'}, RowDat ...

Enhancing ajax requests with headers in Ember.js

My goal is to configure request headers for my emberjs application. However, when setting it up in the initializer, the client_id appears as [object Object] instead of the actual value. This is the initializer that runs when the application starts. Apikey ...

"Duplicate content issue with ng-transclude causing element to render twice

Why is the transcluded directive displaying Name inside directive = Frank twice? I believed I had a good grasp on transclusion, but this specific scenario has left me puzzled. Check out this fiddle for more details <div ng-app="myApp" ng-controller=" ...

The conditional statement for ajax is malfunctioning

I am encountering an issue with some ajax coding. The if condition is not working as expected - whenever the program runs, only the else statement gets executed even when the if statement should be satisfied. <script type="text/javascript> funct ...

Using a series of identical divs to dynamically update the image URL

Greetings! I am a newcomer to the world of web development and I have decided to hone my skills by creating a small website for my mother! My goal is to replicate a specific div multiple times while changing only the image URL and the heading caption. < ...

Incorporate a personalized array into Google Autocomplete Places using AngularJS

I'm working on my application and I've implemented autocomplete for Google Places using the gm-places-autocomplete directive. However, I would like to enhance this autocomplete feature by incorporating my custom array of locations along with the ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

Maintaining Existing Filters and Incorporating Additional Filters in React/Next.js Data Filtering

I'm currently facing a challenge with filtering data in React/Next.js. The issue I'm encountering is that whenever I set a new filter, the previous filters get removed. For instance, if a user performs a search, it works fine but the tag filters ...

What's the reason behind ng-click only functioning with a function and not an assignment within this specific directive?

I am currently working on creating a dynamic table using an array of objects that can be sorted by clicking the headers. I have a specific question regarding how the sorting feature is implemented. let myDirectiveTemplate = ` <table class="directiveTab ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

Generate a fresh Date/Time by combining individual Date and Time components

I have set up a form to gather dates from one input box and times from another. var appointment_date = new Date(); var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)"); var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT- ...

Using Node.js and Typescript to bring in external modules from

Attempting to generate a random integer between 1 and 6 using the 'random' library. Here's what I have coded so far: import random from 'random' function rollDice(min:number, max:number) { return Math.floor(Math.random() * (ma ...

How can I pass an array object from an HTML form that adheres to a Mongoose schema

I have this HTML form that I'm using to create a new document in my mongo database. The document represents notes given to a teacher based on various criteria. I am storing the notes in an array within the note property, each object containing the aut ...

Error: Unable to locate module: 'material-ui/styles/colors'

I encountered an issue with the code below, as it failed to compile: import React from 'react'; import { AppBar, Toolbar } from 'material-ui'; import { Typography } from 'material-ui'; import { MuiThemeProvider, createMuiThem ...

Properties around the globe with Express & Handlebars

Currently, I am utilizing Handlebars (specifically express3-handlebars) for templates and Passport for authentication in my NodeJS application. Everything is functioning smoothly, but I have been contemplating if there is a method to globally pass the req. ...

Updating HTML images in real-time using a combination of Flask and Ajax

I am facing a situation similar to the one discussed in this thread: Flask+AJAX+Jquery+JINJA to dynamically update HTML Table. However, I am struggling to adapt the solution to suit my specific requirements. My objective is to automatically update the imag ...