Initiating the initial element in a list when implementing List with map function in React

Is there a way to automatically trigger the onClick function of the first list item displayed when using the map function in React? I want it to show something, like just logging to the console upon triggering.

...

import React, { useState } from "react";

import ListGroup from "react-bootstrap/ListGroup";
import Container from "react-bootstrap/Container";
import Button from "react-bootstrap/Button";

import "./App.css";

const App = () => {
  const [data, useData] = useState([
    { list: "appelllll" },
    { list: "ballllslsss" },
    { list: "cattsssssss" },
    { list: "dogssssss" },
    { list: "eggssss" },
    { list: "fatssssssssssssssssssss" },
    { list: "goatssssssssssssssss" },
    { list: "heloooooooooooooooooo" },
    { list: "ieloooooooooooooo" },
    { list: "jelooooooooo" },
    { list: "kelooooooo" },
    { list: "leooo" },
    { list: "melosdsadsado" }
  ]);

  return (
    <Container className="p-3">
      <ListGroup
        className="list_menu"
        horizontal
        style={{
          overflowX: "scroll"
        }}
      >
        <button>+</button>
        {data.map((data, i) => {
          return (
            <div>
              <ListGroup.Item
                className="list_item"
                key={i}
                onClick={() => console.log(data)}
              >
                {data.list}
              </ListGroup.Item>
            </div>
          );
        })}
        <button> > </button>
      </ListGroup>
    </Container>
  );
};

export default App;

...

Check out the working code here

Answer №1

In my opinion, the optimal way to approach this is:

onClick={() => {
   if(i === 5)
     console.log(result)
}}

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

The functionality of Jade views is disrupted by external CSS files

I am new to node.js and apologize if this question seems too obvious. I have built my app logic with all the routes and views, and it was working fine until I tried to add more styles to my views using Jade in Express. The only change I made was including ...

Using Scrapy and Selenium to interact with dynamic elements on a webpage

When I crawl the page, I come across an element that looks like this. <a class="a-declarative" href="javascript:void(0)" data-action="a-expander-toggle" data-a-expander-toggle='{"allowLinkDefault":true, "expand_prompt":"See more", "collapse_pro ...

JavaScript - The onkeypress event continuously adds text to the end

In my Angular application, I have implemented an input field with the onkeypress event handler to automatically remove any commas entered by the user: <input name="option" ng-model="main.optionToAdd" onkeypress="this.value = this.value.replace(/,/g ...

Update two distinct object properties using a singular reference in Vue's set method

I'm facing an issue while trying to insert an object into an array using the Vue.set function. The problem is that it adds the item to a different object with the same array property. Here's a snippet of my code: data() { return { ... ...

Can a React Query component be re-rendered after updating the cache?

Within the main component, I retrieved data from the cache like this: const queryClient = useQueryClient(); const data = queryClient.getQueryData('prototypes'); In a different component, after triggering a function, I updated the data in the ...

Vue.js components experiencing issues with updating data

My Vue list is generated from an array where each item renders a component with bound array item properties. <div v-for="item in items"> <item v-bind:item="item"></item> </div> This component contains mixed data based on ...

The second angular $http call fails to reach its intended destination

I am in the process of setting up a flow similar to oauth, where I delay sending an actual request until some initial negotiation has been completed. The initial negotiation is successful, however, when I attempt to make the request for the desired resour ...

Tips for showing a success notification once a PHP script has been successfully completed on a form

Hey everyone, I need some help with a PHP script that I have connected to a single input form. I'm looking to create a success page for users after they submit their email, with a link back. This seems simple enough, but I'm still learning PHP. ...

If you call the jQuery .next method on the last element, what will it return?

Currently, I am facing a challenge where I need to move from one specific row in a table to either another specific row or reach the end of the table. My plan is to examine the value returned by the .next method to ensure that the last node processed was ...

Multer not running when file is uploaded in Node.js with Express using FormData

I have been working on uploading a video file to a local folder using form, multer, express, and nodejs. It seems that the video file successfully gets uploaded to the local folder each time I use the form. However, there is an issue with the code inside ...

How to work with a JSON object in Internet Explorer 6

Looking for some quick answers that should be easy for someone with expertise to provide. I have a basic asp.net site that relies on JSON for various tasks (and JSON.stringify). Everything works fine in Firefox and the like, but in IE6 I'm getting a ...

Fixing the department display list in React Hook: A step-by-step guide

{ roomDept.map((item, index) => ( <div key={index} className="flex flex-col pb-2 items-center"> <div className="flex pb-2 w-full"> <SelectPick ...

What is the best way to line up a number and text using CSS?

Creating a basic gauge meter with min value 0 and max value 2. The current UI progress is as follows: .sc-gauge { width:200px; height:200px; margin:200px auto; } .sc-background { position:relative; height:100px; margin-bottom:10px; background-color:g ...

Change from one value to another using a decaying sinusoidal wave

Can someone help me come up with a formula that will smoothly transition from a starting value to an end value over a specified time using a Sin or Cos wave? I'm attempting to replicate a bouncing effect like the one shown in my sample using CSS and ...

Exploring the front side of a cube using three.js

Exploring the following example: I am curious to know whether it's possible to determine which side of the cube is facing the camera, i.e., the front side. So far, I have been unable to figure this out. Any assistance on this matter would be greatly ...

next.js encountered an issue with the product.map function not being recognized

I am trying to retrieve data from a REST API to display on the front end. I have used getStaticProps() for this purpose, but when I try to map the data from the props, it throws an error saying it is not a function. Upon inspection, I found that the data r ...

I possess 9 captivating visuals that gracefully unveil their larger counterparts upon being clicked. Curiously, this enchanting feature seems to encounter a perplexing issue within the realm of web browsing

<style type="text/javascript" src="jquery-1.11.0.min.js"></style> <style type="text/javascript" src="myCode.js"></style> </body> //jquery is within my site directory on my desktop $(document).ready(function(){ //note: $("#ar ...

Tips on accessing dictionaries with multiple values in JavaScript

I am struggling with a particular dictionary in my code: {1:['a&b','b-c','c-d'],2:['e orf ','f-k-p','g']} My goal is to print the key and values from this dictionary. However, the code I att ...

How can I duplicate an element twice in AngularJS, without having them appear right after each other?

Within my AngularJS template html file, I am faced with a dilemma regarding an html element: <div>This is a complex element that I want to avoid typing multiple times</div> My challenge is that I need this element to show up twice on my websi ...

In my app.post request in node.js and express, the body object is nowhere to be found

Having an issue with node.js and express, trying to fetch data from a post request originating from an HTML file. However, when I log the request, the req.body object appears empty. I've added a console.log(req.body) at the beginning of my app.post(" ...