Search code examples
javascriptreactjsjsxassigninteraction

Way to detect which component is clicked


In my jsx page I have two identical search input components used to filter both company and users data. Is there a way to detect which button has been pressed using React?

<SearchInput label={'Cerca Azienda'} company={company} users={users} setSearchResults={setSearchResults} />

<SearchInput label={'Cerca Utente'} company={company} users={users} setSearchResults={setSearchResults} />


Solution

  • Unfortunately, that is not really possible. However, I'd like to propose an alternative method - a function which returns another function:

    const setSearchResults = (name) => {
        return () => {
            console.log('Setting search results for company', name)
        }
    }
    

    Then, you can simply use it like this:

    <SearchInput label={'Cerca Azienda'} company={company} users={users} setSearchResults={setSearchResults('Cerca Azienda')} />
    
    <SearchInput label={'Cerca Utente'} company={company} users={users} setSearchResults={setSearchResults('Cerca Utente')} />