0

I'm trying to pass a parameter to my redirectSingleLocker function. This function should bring me to the detail page of a specific locker, identified by a guid. The lockerData.map displays all the data from JSON in a table (I left out the code how the lockerData is filled)

Now I wonder how do i pass a parameter to the onClick{} so I can link to the detail page for every record in the table? It allready works properly when using the hardcoded guid which i have commented out in the redirectSingleLocker function. So my only obstacle is how to pass the guid from the lockerData to the redirectSinglelocker function

OrglockerTables.tsx

    const OrgLockerTables: React.FC = () => {

    let history = useHistory();

    function redirectSingleLocker(guid) {
       // let guid = "3x42Q7kU";
       // history.push('/singlelocker?guid='+guid);

       history.push('/singlelocker?guid=' + guid);
    }

    return (
        <table>
        <tbody>
            {
                lockerData.map((lockerData, index) => {
                    console.log('lockers:', lockerData)
                    return (
                        <tr className="row100 body" key={lockerData.id}>
                            {console.log('the id is', lockerData.id)}
                            <td className="column1">{lockerData.id}</td>
                            <td className="column2">{lockerData.guid}</td>
                            <td className="column3">{lockerData.is_currently_claimable}</td>
                            <td className="column4"><button onClick={redirectSingleLocker}></button></td>
                        </tr>
                    );
                }
                )}
        </tbody>
    </table>
    );
};

export default OrgLockerTables;

LockerData Json

{
data: [
{
id: 1,
guid: "3x42Q7kU",
is_currently_claimable: false
},
{
id: 2,
guid: "kLzbAfMc",
is_currently_claimable: true
},
{
id: 3,
guid: "qBqtZ5oR",
is_currently_claimable: true
}
]
}

Any help is greatly appreciated!

Bram
  • 669
  • 3
  • 12
  • 25
  • Have you tried making the `redirectSingleLocker` function expect an argument? Then you could do something like `onClick={ () => redirectSingleLocker(arg) }`. – str8up7od Jan 16 '20 at 23:01

2 Answers2

3

Try this:

<td className="column4"><button onClick={() => {redirectSingleLocker(lockerData.guid)}}></button></td>

you just create an anonymous function as your onClick handler and make that function call your redirectSingleLocker with the guid

fmilani
  • 521
  • 2
  • 9
0
<td className="column4">
  <button onClick={redirectSingleLocker.bind(null, lockerData.guid)} />
</td>

You just need to bind the parameters to the function.

Regarding the bind function, you can refer to this link: What is the use of the JavaScript 'bind' method?

Oceanxy
  • 13
  • 3