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

What is the process for setting environment variables in a Svelte project?

I'm brand new to working with Svelte and I want to incorporate environment variables like base_url into different components. I've read that I can set up a store to hold these values, for example: const DataStore = writable([ { base_url: & ...

Can the outcomes be showcased again upon revisiting a page?

Whenever I navigate away from and return to my filter table/search page, the results vanish. I'm looking for a way to preserve the results without reloading the page. Essentially, I want the page to remain as it was originally, with the search results ...

Images within inline blocks appear to be extending beyond their containing div as though they are

When I check my website in various browsers such as Firefox, IE, Edge, and Safari, I noticed that the images in the "My Specialties" section of the left column are extending outside of the div instead of fitting within it. This problem also occurs in Chrom ...

When using JQuery, the $.each method may not properly iterate through JSON data

I am working on a project where I need to dynamically create HTML checkboxes based on the 'colour' data retrieved from a database in JSON format. My initial approach involves making an AJAX request to a controller: $.ajax({ url: "Home ...

Establish an angular scope within the DOM element

I am facing a challenge in creating a new Angular scope and attaching it to a DOM element. The situation is complicated by the fact that I am working on modifying a third-party control and cannot simply use a directive. My approach so far has been: ... = ...

What is the best way to retrieve SQL results within the parent function's scope in NodeJS?

Currently, I am developing a Brackets text editor extension that stores work time in a database and allows users to view their time entries. The backend is built using Node.js to interact with an SQL server. So far, I have been successful in entering time ...

A guide on implementing AJAX redirection in MVC

I currently have a button that, when clicked, takes input values and redirects to another page in JavaScript using the following code window.location = "Action Param1=value1&Param2=Value2". However, I am looking to avoid using query strings for this me ...

Adjust the color of input labels using jQuery validate

I have a form where I want to change the class of the input labels when a specific field fails validation. My goal is to add the 'error' class to the spans that are directly above any invalid form elements. Here is an example of my HTML structur ...

What is the best way to implement this component into my vue.js project?

I am having trouble integrating this vue component into my app as it is not loading properly. You can find the source of the component here. The following warnings are showing up: Unresolved function or method isNumeric() at line 35 Unused parameter e at ...

Tips for iterating through a collection of arrays with jQuery

I am facing an issue with looping through an array of arrays and updating values or adding new keys to each array. Here is my current setup: var values = []; values['123'] = []; values['456'] = []; values['123&apo ...

vue-form and vue-material are not compatible with each other

In my experience, using a Vue form on a regular HTML <input> element allows validation to work as expected. However, when I switch to using the <md-input> element, the validation no longer functions and an error message is displayed: Element ...

Is there a way to segment a string into words using a dictionary and finding the longest match in JS/Jquery?

Imagine you have a string like this: var str = "thisisinsane"; and a list of words from a dictionary such as: var dic = [ "insane", "i", "is", "sin", "in", "this", "totally" ]; How can we separate the words in str? In this specific case, there a ...

Is there a method to give a webpage a subtle shimmering effect without utilizing CSS box-shadow?

Struggling to Develop a High-Performance Interface Feature I'm currently facing a challenge in coding an interface that requires a subtle and broad glow effect, similar to the example provided below: Exploration of Possible Solutions After expl ...

Maintain form activity post submission using jQuery's addClass and removeClass methods

There is a button on my website that, when clicked, reveals a form. The code I am using for this functionality is: $('#theform').addClass('hidden') $('#theform').removeClass('hidden'); <div id="theform" c ...

Is there a way to refresh a Material-UI data table in React whenever a user takes any action?

I am facing an issue with my Lock-Unlock button and delete button. The problem arises when I render data from axios using the useEffect hook, it works fine. However, if I try to lock or unlock a user, the table does not update automatically. This indicates ...

Explore numerous classes using the useRef method

I am facing a challenge in accessing all classes rendered using the map() function. The code snippet below illustrates my current situation: {arr.map((i, k) => { return <div ref={car} className={`car-nr-${i.id}`} key={k}}> </div> })} Cur ...

Preventing clicks within an iframe

Within an iframe, I have HTML content that includes hyperlinks. I need to prevent clicks on these hyperlinks. I managed to accomplish this using jQuery as shown below. However, I prefer not to use jQuery for this task. How can I achieve the same result ...

Having trouble loading the script from the assets 'index.android.bundle'? Ensure that your bundle is properly packaged or that you have a packager server running

I encountered an issue while updating my React Native application from version 0.38.0 to 0.45.1. The error message I received is as follows: java.lang.RuntimeException: Unable to load script from assets 'index.android.bundle'. Make sure your bun ...

Encountering undefined errors when attempting to parse intricate JSON data from a file in ReactJS

As I work on processing data from files and integrating third-party services to save the information back into files, here is a snippet from one of the sample files: { "tag": "#8GYVRVG", "name": "Warrior", "expLevel": 13, "trophies": 5634, ...

Encountering a problem with Chrome Extension localization upon installation - receiving an error message claiming default locale was not specified, despite having

Error Message: "The package has been deemed invalid due to the following reason: 'Localization was utilized, however default_locale was not specified in the manifest.' Issue: I have developed a customized extension and defined a default locale, ...