Tuesday, August 2, 2022

[FIXED] How can I make each row of my table dynamic when I click on it?

Issue

I have the following table made in Django and I want to do the same but with react.

I want each row in my table to be clickable with a dynamic link pointing to said record.

Example:

<tbody>
  {% for i in inventories %}
  <tr onclick="location.href='/inventory/detail/{{i.id}}'">
    <td>{{i.name}}</td>
  </tr>
  {% endfor %}
</tbody>

React:

<Tbody>
  {companies.map((company, index) => (
    <Tr key={index}>
      <Td>{company.company_id}</Td>
      <Td>{company.social_reason_name}</Td>
      <Td>{company.comercial_name}</Td>
      <Td>{company.alias_name}</Td>
      <Td>{company.rnc}</Td>
    </Tr>
  ))}
</Tbody>

How can I make each Tr row in the table become a dynamic link?


Solution

Import the Link component and wrap the row content. Compute and pass the target path to the Link component's to prop.

Example:

import { Link } from 'react-router-dom';

...

<Tbody>
  {companies.map((company, index) => (
    <Tr key={index}>
      <Link to={`/company/detail/${company.company_id}`}>
        <Td>{company.company_id}</Td>
        <Td>{company.social_reason_name}</Td>
        <Td>{company.comercial_name}</Td>
        <Td>{company.alias_name}</Td>
        <Td>{company.rnc}</Td>
      </Link>
    </Tr>
  ))}
</Tbody>


Answered By - Drew Reese
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.