Generating a hyperlink to a specific user ID within a data table

I'm facing an issue with the formatting of my simple table when trying to navigate to user.id. Is there a better approach to this or should I consider moving LinkToUser?

All styling has been removed to avoid any conflicts.

import styled from 'styled-components'
import { Link } from 'react-router-dom'

export const LinkToUser = styled(Link)`
`

export const StyledTable = styled.table`
`;

export const THead = styled.thead`
`;

export const TR = styled.tr`
`;

export const TBody = styled.tbody`
`;

export const TH = styled.th`
`;

export const TD = styled.td`
`;

    <StyledTable>
        <THead>
            <TR>
                <TH>{copy.tableHeaderA}</TH>
                <TH>{copy.tableHeaderB}</TH>
                <TH>{copy.tableHeaderC}</TH>
            </TR>
        </THead>
        <TBody>
            {fetchedUsersData?.map((user: Users) => (
                <LinkToUser to={`/users/${user.id}`}>
                    <TR key={user.id}>
                        <TD>
                            <p>{user.username}</p>
                        </TD>
                        <TD>
                            <p>{user.name}</p>
                        </TD>
                        <TD>
                            <p>{user.company.name}</p>
                        </TD>
                    </TR>
                </LinkToUser>
            ))}
        </TBody>
    </StyledTable >

https://i.sstatic.net/VoHf4.png

Answer №1

For those utilizing react-router-dom in React, utilize onClick and history

<StyledTable>
        <THead>
            <TR>
                <TH>{copy.tableHeaderA}</TH>
                <TH>{copy.tableHeaderB}</TH>
                <TH>{copy.tableHeaderC}</TH>
            </TR>
        </THead>
        <TBody>
            {fetchedUsersData?.map((user: Users) => ( 
                    <TR key={user.id}
                     onClick={()=>{
                      history.push(`/users/${user.id}`)
                     }
                    >
                        <TD>
                            <p>{user.username}</p>
                        </TD>
                        <TD>
                            <p>{user.name}</p>
                        </TD>
                        <TD>
                            <p>{user.company.name}</p>
                        </TD>
                    </TR> 
            ))}
        </TBody>
    </StyledTable >

Answer №2

To optimize your code, remember to move the key to the parent component within the map function as shown below: Update this snippet:

{fetchedUsersData?.map((user: Users) => (
                <LinkToUser to={`/users/${user.id}`}>
                        <TR key={user.id}>

to:

{fetchedUsersData?.map((user: Users) => (
                <LinkToUser to={`/users/${user.id}`} key={user.id}>
                    <TR >

Ensure that the table is part of the router parent tree. If you encounter difficulty having a Link directly within TableBody, consider moving the link inside one of the TD elements.

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

Struggling with passing the decoded user ID from Node Express() middleware to a route can be problematic

I have encountered a similar issue to one previously asked on Stack Overflow (NodeJS Express Router, pass decoded object between middleware and route?). In my scenario, I am using the VerifyOrdinaryUser function as middleware in the favorites.js route. Th ...

Tips for horizontally aligning an item in a flexbox only when it wraps onto a new line

In my layout, I have a container that consists of text on the left and a button on the right. The challenge I'm facing is ensuring proper alignment when they are on the same line versus when the button wraps to a new line on smaller screens. Ideally, ...

The export button in the React Material Table doesn't seem to be displaying correctly

[I am encountering an issue with the React export button in Material Table. The bar is not showing completely. My code includes the following: options = {{exportButton:true}} How can I resolve this?]1 ...

I am puzzled as to why my DataGrid MUI component is not functioning properly

I am taking my first steps with MUI, the MaterialUI React Component library. After following the installation instructions in the documentation, I am now attempting to integrate the DataGrid component into my React project. My goal is to replicate the fir ...

Guide on modifying CSS properties when hovering over the parent element

I am working with a table structure like this: <table> <tr><td class="momdad"><i class='glyphicon glyphicon-cog'></i> Hello </td><td> Mom </td></tr> <tr><td class="momdad">< ...

Uploading files in javascript and PHP

I am currently utilizing an audio recorder provided by this source , However, instead of storing the file locally, I am interested in uploading it back to the server. My attempt involved adjusting the Recorder.setupDownload function within the recording. ...

FirebaseError: The type 'Hc' was expected, but instead, a custom Yc object was provided

I've encountered an issue while attempting to perform a batch entry. The error I'm facing involves passing an array in a .doc file. Interestingly, this approach seems to work perfectly fine on another function where I pass an array into a .doc us ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Are HTML5 Track Element Cue Events Working Properly?

My goal is to dynamically assign functions to HTML5's cue.onenter events. This feature is relatively new and currently only supported in Chrome with specific flags enabled (Refer to the example on HTML5 Rocks here). However, I seem to be facing some ...

Alert: '[Vue warning]: Directive "in testing" could not be resolved.'

Currently, I am running unit tests within a Vue 2.0 application using PhantomJS, Karma, Mocha and Chai. Although the tests are passing successfully, I am encountering a warning message with each test indicating an issue like this: ERROR: '[Vue warn ...

Delete an entry from the list

I have a fully functional Ajax call and function that fills up a datalist. This datalist is utilized to choose from a limited list and add it to a UL element on the page. Once an option is added from the datalist to the actual list, I aim to eliminate that ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...

What is the best way to retrieve all href links within a ul element on a webpage that includes a scrollbar?

I am trying to extract all href links that are within the list items (li) in this specific unordered list (ul): Click here to view the screenshot Here is my current code snippet: import bs4, requests, re product_pages = [] def get_product_pages(openurl) ...

Adjust the display of inline-block divs to disregard line breaks

I am having an issue with three side-by-side divs using the display:inline-block property. When the divs are empty, they all align perfectly on the same horizontal level. However, once I add <p> tags and some line breaks (<br/>) to the first ...

What is the proper way to declare a Type for a JSX attribute in Google AMP that utilizes square brackets?

When utilizing AMP's binding feature, you must apply specific attributes that encapsulate an element's property with square brackets and connect it to an expression. An example from AMP is shown below: <p [text]="'Hello ' + foo"> ...

What are the most effective techniques for setting up headers in a table for optimal organization?

I have a dataset in a table format and I am looking to adjust the spacing to avoid overcrowding. At the same time, I want the title row of the table to not follow the same spacing rules as the rest of the cells. Is there a way to achieve this without crea ...

Encountering an error when attempting to assign a value within the onChange callback of a React dropdown component

I have implemented a Dropdown component using react-dropdown to show a list of options. I am facing an issue where, upon selecting an option from the list for the first time, the value changes successfully. However, upon selecting a second option, it thr ...

Making Bootstrap Carousel images slide seamlessly

Can someone help me with implementing Bootstrap carousel slides that display gif short clips when transitioning to the next page? I've searched through Bootstrap documentation and Stack Overflow for solutions, but I can't seem to get the slide to ...

Personalize the TableRow using the Material UI component

Currently, I am working with the Material UI table example and attempting to customize the rows by implementing my own component to replace the default row. My goal is to add some margin between the rows and introduce a shadow using the elevation prop of t ...

Updating data in a SQL database using PHP when a button is clicked

This Question was created to address a previous issue where I had multiple questions instead of focusing on one specific question Objective When the user selects three variables to access data, they should be able to click a button to modify one aspect o ...