Display a message with `console.log` when a button is clicked in

I would like the console.log to display the coin.id of the element when I click on the row element.

import React, { useState, useEffect } from "react";
import { Col, Image, Row } from "react-bootstrap";
import "./Company.scss";

// * api
import { getCoin } from "../services/api";

// *spinner
import Loader from "./Loader";

const Company = () => {
  const [selectedCoin, setSelectedCoin] = useState(null);
  const [coins, setCoins] = useState([]);

  useEffect(() => {
    const fetchAPI = async () => {
      const data = await getCoin();
      setCoins(data);
    };
    fetchAPI();
  }, []);

  return (
    <>
      {coins.length > 0 ? (
        coins.map((coin) => (
          <Row
            className={
              selectedCoin === coin.id
                ? "p-2 border-top d-flex align-items-center company-list-single-active"
                : "p-2 border-top d-flex align-items-center company-list-single"
            }
            onClick={() => {
              setSelectedCoin(coin.id);
            }}
            key={coin.id}
          >
            <Col xxl="2" xl="2" lg="3" md="3" sm="2" xs="2">
              <Image
                src={coin.image}
                alt={coin.name}
                className="coin-image mx-2"
                fluid
              />
            </Col>
            <Col>
              <span>{coin.name}</span>
            </Col>
          </Row>
        ))
      ) : (
        <Loader />
      )}
    </>
  );
};
export default Company;

screenshot project

Answer №1

If you want to include an additional function call (such as console.log()) within the anonymous function for the onClick event handler, you are able to do so

onClick={() => { 
  console.log(coin.id);
  setSelectedCoin(coin.id);        
}} 

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

What is the best way to automatically select options in a dynamic dropdown menu

In my code, I have a list of user records. One column has a dropdown to change the produced by. The ng-change function is working fine. However, after refreshing the page, the dropdown does not show the last selected option. Please review my code below - ...

Implement JQuery UI Accordion to enhance navigation on mobile devices

I am implementing the JQuery UI Accordion to expand content on a website. Below is the basic markup structure: <div class="accordion"> <h2>Heading</h2> <div>Content</div> <h2>Heading</h2> <div& ...

A regular expression in JavaScript for matching unpredictable numbers without any specific words preceding them

For instance, I am looking to extract the numbers that do not have 'the', 'abc', or 'he' before them; the89 (no match) thisis90 (match 90) iknow89999 (match 89999) getthe984754 (no match) abc58934(no match ...

What is preventing my Express.js from running properly?

My express.js application stops running after reaching this point: node app.js info - socket.io started I'm looking for guidance on why this error occurs and how to resolve it. It seems like the issue lies within my app.js file, which I've inc ...

Mastering the art of ajax and j Query integration with Spring

I'm fresh to working with Spring and AJAX. My task involves checking whether an email is already registered or not when the user clicks on "check availability." I can successfully make calls to the controller class, but the response is being displaye ...

Error: req.body or req.params.id is not defined in the current context (PUT and PATCH requests)

I'm experiencing an issue where both req.body and req.params.id are returning undefined even though I am using express.json() before the app.patch. I have tried changing the route to /:id, but that did not resolve the problem. Interestingly, it works ...

skip every nth element in the array based on the specified value

The Challenge I'm currently working on a graph that relies on an array of data points to construct itself. One major issue I've encountered is the need for the graph to be resizable, which leads to the necessity of removing certain data points ...

Executing cssnano Using the Command Prompt

Although I'm not an expert in node JS, I have come across cssnano as a JavaScript tool for minifying CSS, which apparently does a more sophisticated job compared to the outdated YUI compressor. My only issue is that I am struggling to understand how t ...

Updating the JWT token in Angular 6 and making a new request with the updated token

When my JWT authentication token expires (verified by the backend), I need to call a refresh token API and resend the last failed request due to the expired token. I have an Interceptor in place, but I must update the authentication header before sending ...

Tips on aligning elements and incorporating icons in Bootstrap list items

Struggling to center an icon with text? Trying to achieve alignment of SVG + text while utilizing Bootstrap? You're not alone. Don't worry - I have the solution. Check out my before and after samples: Before After But here are some questions that ...

Flick user media cards left or right to uncover the following one

I am currently working on creating a widget that will display user media objects in a horizontal layout using ng-repeat. The goal is to allow users to swipe left or right to reveal the next media card, similar to the image shown below. In the example, you ...

When hovering over a specific div, it triggers a hover effect on a separate div

Currently, I am facing a dilemma: I have an effect triggered by hovering over one div, but I actually want the effect to be triggered when the cursor hovers over another div instead. To illustrate: <div id='mouse-hover-in-this-div'> bl ...

ReferenceError: source is not defined in Gulp with Browserify

I encountered a strange error while working on my project. The error message I received is as follows: $ gulp browserify [01:21:03] Using gulpfile F:\CSC Assignments\FinalProject\HotelProject\gulpfile.js [01:21:03] Starting 'bro ...

Having trouble with reloading or navigating directly to a dynamic route in Next JS?

Having an issue with NextJS - specifically with dynamic routes on a few pages: queries/[id].tsx queries/index.tsx During development, everything works fine when accessing: https://localhost:3006/queries/1324 The problem arises after building the project, ...

Node.js Cross-Origin Resource Sharing error

Struggling with building a web application using NODE and React without Express router due to CORS issues arising from running both on different ports. Despite wanting to stick to the native http module provided by node, the lack of access to the CORS midd ...

What steps should be taken to resolve the nodemon error related to block-scoped declarations?

Below is the content of my package.json file: { "name": "pro-mern-stack", "version": "1.0.0", "description": "initial version", "main": "index.js", "scripts": { "start": "nodemon server.js server.js", "compile": "babel src --presets rea ...

Deactivate checkbox based on dropdown selection

I'm facing an issue where I need to disable a checkbox when a certain option is selected from a dropdown inside a datatable in my xhtml file. The dropdown has options like L, C, UV, and more, and when "L" is chosen, the checkbox should be disabled. B ...

JavaScript Selenium code encountering an "Element not interactable" error with input textbox element

Currently, I am attempting to utilize Selenium in order to automate inputting a location into the search bar on weather.com. Initially, I wrote the code in Python and it seems to be functioning properly: // this works driver = webdriver.Chrome(ChromeDriver ...

Creating equal-sized borders for symbols of varying sizes: a step-by-step guide

Utilizing Font Awesome icons along with their fa-border style: <i class="fa fa-twitter fa-5x fa-border icon-blue"></i> <i class="fa fa-question fa-5x fa-border icon-grey"></i> The border size created varies based on the symbol siz ...

In an MVC 4 application, when using JQuery to replace HTML and then calling the .show() function, the

I have a null div element: <div id="reportBody"></div> with basic styling: #reportBody { height: 100%; } The reportBody div is located within a hidden modal that is triggered by a button click. I am using jQuery and AJAX to call a contro ...