Dženis H.
Dženis H.

Reputation: 7822

How to know which element was clicked when using map function and how to pass that value to another component?

sortedReports.map(item => {

    return (
    <tr key={item.rowNumber}>
        <td>  {item.year}</td>

        <td> {item.month}</td>

        <td> {item.bruto_ukupno}</td>
        <td> {item.neto_plata}</td>
        <td> {item.topli_obrok}</td>

        <td> {item.doprinosi}</td>
        <td> {parseInt(item.ukupno_plata)}</td>

        <td className="table-actions">
            <Link **onClick={}**

                    to={`/reports/details`}>
                <PieChart size="21"/>
            </Link>

        </td>
    </tr>
)});

I need to get the clicked, store its value and pass it to another component where I need to filter employees depending on which reports month was clicked.

THANK YOU SO MUCH :)

Upvotes: 0

Views: 629

Answers (2)

Matt Condit
Matt Condit

Reputation: 27

I would utilize currying to create functions "bound" (but not in the .bind sense) to the value of that item. i.e.

// as a class method
const createClickHandler = (itemValue) => e => {
   //...doStuff
};

Then utilize it by passing the item value when mapping.

<Link onClick={this.createClickHandler(item)}
      to={`/reports/details`}>
      <PieChart size="21"/>
</Link>

Upvotes: 1

smee
smee

Reputation: 231

You can pass the item as an extra argument to bind(). List his:

sortedReports.map(item => {

    return (
    <tr key={item.rowNumber}>
        <td>  {item.year}</td>

        <td> {item.month}</td>

        <td> {item.bruto_ukupno}</td>
        <td> {item.neto_plata}</td>
        <td> {item.topli_obrok}</td>

        <td> {item.doprinosi}</td>
        <td> {parseInt(item.ukupno_plata)}</td>

        <td className="table-actions">
            <Link onClick={this.handleClick.bind(this,item)}
                to={`/reports/details`}>
                <PieChart size="21"/>
            </Link>

        </td>
    </tr>
)});

And then handleClick might look like this:

handleClick(item) {
    // Do what you want on click
}

I'm binding the entire selected object here, but you could bind just the item.rowNumber if that makes the code cleaner elsewhere.

Upvotes: 0

Related Questions