Mastering the Art of Displaying Links in Columns within a Table Using ReactJS

I have the following code that fetches data from the backend and displays it in a table. Everything is working correctly. Now, I need to make the first column in the table appear as a link. How can I achieve that?

const EditController = () => {

    const initState = [
        {name: "", ipaddr: "", port: 0, sshuser: "", sshport: 0, license: ""},
    ];
    
    const [state, setState] = useState(initState);
    const user = localStorage.getItem("user");
    const token = localStorage.getItem("jwt");
    
    const fetchControllers = async () => {
        try {
            const res = await axios.post('/exec/editcontroller', {user} , {headers: {
              'Content-Type': 'application/json',
              'Authorization': token,
            }}).then( function (res) {
                
                if(res.status === 200) {
                    setState(res.data);
                }else {
                    return 'failure';
                }
                
            });
        }catch(err) {
            return 'error';
        }
    }
    
    useEffect ( () => {
       console.log('Inside useEffect');
       fetchControllers();
    }, []);
        
    return (
        <div className="medium-text">
            <div className="center">
                <h2>Controllers</h2>
                <table id="tbl">
                
                    <thead>
                        <tr>
                            <th><a href="#">Name</a></th>
                            <th>IP Address</th>
                            <th>Port</th>
                            <th>SSH User</th>
                            <th>SSH Port</th>
                            <th>License</th>
                        </tr>
                    </thead>                
                    
                    {state.map((item) => (
                        <tr key={item.id}>
                        {Object.values(item).map((val) => (
                            <td>{val}</td>
                        ))}
                        </tr>
                    ))}
                
                </table>    
            </div>
        </div>
    );
}

export default {EditController};

Answer №1

To simplify things, utilize the index within the map function.

 {Object.values(item).map((value, count) =>
    count === 0 ? (
        <td>
            <Link href='/'>{value}</Link>
        </td>
            ) : (
        <td>{value}</td>
            )
        )}

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

Starting a new container causes another container to halt

Having created two basic MEAN stack apps that share a common MongoDB database, I successfully dockerized both applications. Issue: When starting the first mean stack container (example-app-1) using docker-compose up -d --build The container runs smoot ...

Capture and transform every alert into a notification

I have implemented Gritter for notifications across my website and am curious if there is an easy method to intercept all alert() messages triggered by scripts using jQuery, and then display the contents of the alert in a Gritter notification. Is there a ...

How can one transform a json object into a json string and leverage its functionalities?

I recently encountered an issue with a JSON object that contains a function: var thread = { title: "my title", delete: function() { alert("deleted"); } }; thread.delete(); // alerted "deleted" thread_json = JSON.encode(thread); // co ...

Executing jQuery script on dynamically loaded content

My website utilizes AJAX requests to load pages dynamically. One specific page includes a marquee script that I would like to implement. Unfortunately, due to the dynamic loading of the page, the marquee script is not functioning as expected. I have come ...

The combination of Express 3.0, Everyauth, and HTTPS creates a powerful

Currently, I am working with nodejs and using express 3 along with everyauth for google oauth. The setup appears as follows: everyauth.google /* snip */ .callbackPath('/loggedin'); var app = express(); app.configure(function(){ /* snip */ ...

Start a timer in CodeIgniter when a button is clicked and show the time elapsed

Just a heads up: I am currently in the learning process. While I have some experience with PHP, my knowledge of Java is very limited or non-existent. In the past, I've received negative feedback due to this lack of experience. So, here I am giving it ...

The deserializeUser function in PassportJS is being ignored

My setup involves using Passport to authenticate users stored in mongodb. Everything seems to be working fine with authentication, including successful and failed login attempts as well as setting session variables. However, I am facing an issue where Pass ...

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

Encountering difficulties with the installation of Ionic's software

Having trouble installing Ionic on Windows and running into issues with the npm commands. Despite a successful "npm install" command, when trying to run an Ionic command like "ionic start," or even just "ionic -version," the shell responds with "'Ioni ...

Update nested child object in React without changing the original state

Exploring the realms of react and redux, I stumbled upon an intriguing challenge - an object nested within an array of child objects, complete with their own arrays. const initialState = { sum: 0, denomGroups: [ { coins: [ ...

Deleting the stylesheet exclusively within the confines of the React application window

Here is an image that will help illustrate the issue: https://i.stack.imgur.com/VA7fw.png If you want to check out the code sandbox for this problem, you can visit: https://codesandbox.io/s/annoying-stylesheet-2gpejc?file=/public/index.html I am current ...

There seems to be an issue as req.files in Sails.js is blank and the value of req

I've been struggling with this problem for quite some time now. Despite my efforts to find a solution through Google and StackOverFlow, I have not been successful. The issue lies within a project I am working on, where I have implemented a "Product" M ...

Exploring Collections and Retrieving Information in MongoDb

Struggling with Establishing Relations in MongoDB Collection for REST API Data Retrieval As a newcomer to NodeJs and MongoDB, my goal is to build a REST API that retrieves data on categories and products. Specifically, I want to establish a connection bet ...

Firefox: Issue with CSS aspect ratio not being supported in Firefox, unlike Chrome which works correctly

For my application, I am utilizing the display: grid property. My goal is to have the grid items always maintain a square shape by applying an aspect ratio of 1/1. While this works perfectly in Chrome, Firefox seems to ignore the aspect ratio code. Even co ...

Display a flash message to the user indicating the status of a fetch/ajax request

I currently have an application that relies on the fetch API for AJAX operations related to CRUD functionality. After a successful or failed operation, my server returns a response containing an array of messages indicating success or errors, such as: [&ap ...

convert webpages and images to PDF with a custom watermark

Looking to convert images fetched from the server into PDF format with a watermark by clicking a button. It would be ideal if there is a plugin that allows for PDF preview with disabled user selection and copy options. The website's platform is Sales ...

Does the downloading of images get affected when the CSS file has the disabled attribute?

Is it possible to delay the download of images on a website by setting the stylesheet to 'disabled'? For example: <link id="imagesCSS" rel="stylesheet" type="text/css" href="images.css" disabled> My idea is to enable the link later to tri ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...

The Formik and React error is indicating that the '{ refetch: any; }' type is absent

When attempting to pass a prop down to my EmailSignupScreen, I encountered an error message. This issue arose while experimenting with Formik and Typescript. "message": "Type '{ refetch: any; }' is missing the following properties from type &apo ...

Is there a way to invoke a different function within a class from a callback function in an HTTP request?

Having an issue with my HTTP GET request function in the "CheckPrice" class. When trying to call another function within the class callback, it's showing as undefined. Any suggestions? const got = require("got") class PriceCheck { constructor() { ...