How to dynamically calculate gradient percentage

I have an array which has dynamic values from server

let arr = ['#eee','#fff','#aaa']
or sometimes,
let arr = ['#eee','#fff','#aaa','#eee','#fff','#aaa']

Now, I need to calculate the gradient values. I did something like below which is giving some wrong value.

let arr = ['#eee','#fff','#aaa','#eee','#fff','#aaa']

let gper = parseFloat(100/arr.length)

let c_arr = arr.map((k, i) => {  return `${k} ${parseFloat(gper * i--)}% ${parseFloat(gper * i)}%`})
               .toString()
               
console.log(`linear-gradient(to left, ${c_arr})`)

Is there a best way to fix this

how would i make a widget work with nodejs

So I am facing a dillema. I have a widget that needs to get data from a nodejs app. The nodejs returns some results. I simply want to plug those results into the entryID property found in this widget, but unsure how to make it gel. Would i make a call to a script.js file that has my nodejs scripts?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnapisec.kaltura.com/p/3048041/sp/304804100/embedIframeJs/uiconf_id/46dsd371/partner_id/3042043"></script>
<div id="player_1639699783" style="width: 560px; height: 395px;"></div>
<script>
kWidget.embed({
"targetId": "kaltura_player_1639699783",
"wid": "_304dsd1",
"uiconf_id": dsddd,
"flashvars": {},
"cache_st": 1639699783,
"entry_id": "1_4u0ocu4u"
});
</script>

How to configure razorpay in react?

i had developedcar booking app but here i am facing an issue when click on booknow button it has to pass the one object and has th launch the razorpay payment and after payment succeess it has to redirect to bookings page but when i click on buynow button it opening the razorpay model and redirecting to bookings page.
Please look into my code and help me

BookingCar.js

import React, { useEffect, useState } from "react";
import DefaultLayout from "../components/DefaultLayout";
import { useSelector, useDispatch } from "react-redux";
import { getAllCars } from "../redux/actions/carsActions";
import { useParams } from "react-router-dom";
import Spinner from "../components/Spinner";
import { Row, Col, Divider, DatePicker, Checkbox, Modal } from "antd";
import moment from "moment";
import { bookCar } from "../redux/actions/bookingAction";
import StripeCheckout from "react-stripe-checkout";

const { RangePicker } = DatePicker;

function BookingCar() {
  const { carid } = useParams();
  const { cars } = useSelector((state) => state.carsReducer);
  const { loading } = useSelector((state) => state.alertsReducer);
  const [car, setCar] = useState([]);
  const [to, setTo] = useState();
  const [from, setFrom] = useState();
  const [totalHours, setTotalHours] = useState(0);
  const [driver, setDriver] = useState(false);
  const [totalAmount, setTotalAmount] = useState(0);
  const [showModal, setShowModal] = useState(false);
  const dispatch = useDispatch();

  useEffect(() => {
    if (cars.length == 0) {
      dispatch(getAllCars());
    } else {
      setCar(cars.find((o) => o._id == carid));
    }
  }, [cars]);

  useEffect(() => {
    setTotalAmount(totalHours * car.rentPerHour);
    if (driver) {
      setTotalAmount(totalAmount + totalHours * 100);
    }
  }, [driver, totalHours]);

  function selectTimeSlots(values) {
    console.log(moment(values[0]).format("MMM DD YYYY HH:mm"));
    console.log(moment(values[1]).format("MMM DD YYYY HH:mm"));
    setFrom(moment(values[0]).format("MMM DD YYYY HH:mm"));
    setTo(moment(values[1]).format("MMM DD YYYY HH:mm"));
    setTotalHours(values[1].diff(values[0], "hours"));
  }

  const launchRazorpay = () => {
    var options = {
      key: process.env.REACT_APP_RAZORPAY_KEY_ID,
      amount: totalAmount * 100,
      currency: "INR",
      name: "Acme Corp",
      description: "Test Transaction",
      image: "https://example.com/your_logo",
      handler: function (response) {
        alert(response.razorpay_payment_id);
        alert(response.razorpay_order_id);
        alert(response.razorpay_signature);
      },
    };
    let razorpay = new window.Razorpay(options);
    razorpay.open();
  };

  function bookNow() {
    const reqObj = {
      user: JSON.parse(localStorage.getItem("user"))._id,
      car: car._id,
      totalAmount,
      totalHours,
      driverRequired: driver,
      bookedTimeSlots: {
        from,
        to,
      },
    };

    dispatch(bookCar(reqObj));
    launchRazorpay();
  }

  return (
    <DefaultLayout>
      {loading == true && <Spinner />}
      <Row
        justify="center"
        className="d-flex align-items-center"
        style={{ minHeight: "90vh" }}
      >
        <Col lg={10} sm={24} xs={24} className="p-3">
          <img src={car.image} className="carimg2 bs1 w-100 p-2" />
        </Col>
        <Col lg={10} sm={24} xs={24} className="text-right">
          <Divider type="horizontal" dashed>
            Car Info
          </Divider>
          <div style={{ textAlign: "right" }}>
            <p>{car.name}</p>
            <p>{car.rentPerHour} per hour /-</p>
            <p>Fuel Type: {car.fuelType}</p>
            <p>Max Capacity: {car.capacity}</p>
          </div>
          <Divider type="horizontal" dashed>
            Select Time Slots
          </Divider>
          <RangePicker
            showTime={{ format: "HH:mm" }}
            format="MMM DD YYYY HH:mm"
            onChange={selectTimeSlots}
          />
          <br />
          <button
            className="btn1 mt-3"
            onClick={() => {
              setShowModal(true);
            }}
          >
            Booked Time Slots
          </button>
          {from && to && (
            <div>
              <p>
                Total Hours: <b>{totalHours}</b>
              </p>
              <p>
                Rent Per Hour: <b>{car.rentPerHour}</b>
              </p>
              <Checkbox
                onChange={(e) => {
                  if (e.target.checked) {
                    setDriver(true);
                  } else {
                    setDriver(false);
                  }
                }}
              >
                Driver Required{" "}
              </Checkbox>
              <h3>Total Amount: {totalAmount}</h3>

              <button className="btn1" onClick={bookNow}>
                Book Now
              </button>
            </div>
          )}
        </Col>
      </Row>
      <Modal
        visible={showModal}
        closable={false}
        footer={false}
        title="Booked Time Slots"
      >
        {car && (
          <div className="p-2">
            {car.bookedTimeSlots?.map((slot) => {
              return (
                <button className="btn1 mt-2">
                  {slot.from} - {slot.to}
                </button>
              );
            })}
            <div className="text-right mt-5">
              <button className="btn1" onClick={() => setShowModal(false)}>
                CLOSE
              </button>
            </div>
          </div>
        )}
      </Modal>
    </DefaultLayout>
  );
}

export default BookingCar;

bookingRoute.js

const express = require("express");
const router = express.Router();
const Booking = require("../models/bookingModel");
const Car = require("../models/carModel");
const { v4: uuidv4 } = require("uuid");
const Razorpay = require("razorpay");
require("dotenv").config();
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);

router.post("/bookcar", async (req, res) => {
  var razorpay = new Razorpay({
    key_id: "rzp_test_2lNx88Blumt0AQ",
    key_secret: "C04AFyyG9GTcT6bO6HWZ18mv",
  });
  var options = {
    amount: req.body.totalAmount * 100,
    currency: "INR",
    receipt: "sn_booking_001122",
  };
  console.log(options);
  razorpay.orders.create(options, (err, order) => {
    console.log(order);
    return res.send(order);
  });
  // try {

  //   req.body.transactionId = "Ordr_123";
  //   const newBooking = new Booking(req.body);
  //   await newBooking.save();
  //   const car = await Car.findOne({ _id: req.body.car });
  //   car.bookedTimeSlots.push(req.body.bookedTimeSlots);
  //   await car.save();
  //   res.send("Your Booking is Successful");
  // } catch (error) {
  //   return res.status(400).send(error);
  // }
});

router.get("/getallbookings", async (req, res) => {
  try {
    const bookings = await Booking.find().populate("car");
    res.send(bookings);
  } catch (error) {
    return res.status(400).json(error);
  }
});

module.exports = router;

bookingAction.js

import axios from "axios";
import { message } from "antd";

export const bookCar = (reqObj) => async (dispatch) => {
  dispatch({ type: "LOADING", payload: true });
  // const baseurl = "http://localhost:4500";
  try {
    await axios.post(`/api/bookings/bookcar`, reqObj);
    dispatch({ type: "LOADING", payload: false });
    setTimeout(() => {
      message.success("Your Car Booked Successfully");
      window.location.href = "/mybookings";
    }, 500);
  } catch (err) {
    console.log(err);
    dispatch({ type: "LOADING", payload: false });
    message.error("Something went wrong, Please try again later");
  }
};

export const getAllBookings = () => async (dispatch) => {
  dispatch({ type: "LOADING", payload: true });
  // const baseurl = "http://localhost:4500";
  try {
    const response = await axios.get(`/api/bookings/getallbookings`);
    dispatch({ type: "GET_ALL_BOOKINGS", payload: response.data });
    dispatch({ type: "LOADING", payload: false });
  } catch (err) {
    console.log(err);
    dispatch({ type: "LOADING", payload: false });
  }
};

ReactJS best way to animate image zoomin/out from grid item to screen width

I just started learning React and i’m making a clone of the website surviveicarus as my 1st ever React project to learn the basic stuff. I think the website looks complicated enough for me to learn enough about how React works and maybe learn some more CSS.
I struggle figuring out how to animate zooming in an image from a grid item to full screen width without messing with the grid. Should i make another element and pass the image property to it and show it on the screen or can it be done with the current div element holding the image.

Gallery container:

import React, { useState } from 'react'
import { BsArrowsAngleExpand } from 'react-icons/bs';

import Image1 from "../../images/gallery/Gallery_Wolves.jpg";
import Image2 from "../../images/gallery/Gallery_Orbit.jpg";
import Image3 from "../../images/gallery/Gallery_Lightning.jpg";
import Image4 from "../../images/gallery/Gallery_Hunting.jpg";
import Image5 from "../../images/gallery/Gallery_Building.jpg";
import Image6 from "../../images/gallery/Gallery_Desert.jpg";

import { GalleryContainer, ImageHolder, GalleryImage } from './GalleryElements'

function GallerySection() {
    const [ imageOpen, setImageOpen ] = useState(false);
    const toggleImage = () => { setImageOpen(!imageOpen); console.log(imageOpen) }

    return (
        <GalleryContainer>
            <ImageHolder onClick={toggleImage} imageOpen={imageOpen}>
                <GalleryImage src={Image1} alt="Wolves"/>
                <BsArrowsAngleExpand/>
            </ImageHolder>
            <ImageHolder>
                <GalleryImage src={Image2} alt="Orbit"/>
                <BsArrowsAngleExpand/>
            </ImageHolder>
            <ImageHolder>
                <GalleryImage src={Image3} alt="Lightning"/>
                <BsArrowsAngleExpand/>
            </ImageHolder>
            <ImageHolder>
                <GalleryImage src={Image4} alt="Hunting"/>
                <BsArrowsAngleExpand/>
            </ImageHolder>
            <ImageHolder>
                <GalleryImage src={Image5} alt="Building"/>
                <BsArrowsAngleExpand/>
            </ImageHolder>
            <ImageHolder>
                <GalleryImage src={Image6} alt="Desert"/>
                <BsArrowsAngleExpand/>
            </ImageHolder>
        </GalleryContainer>
    )
}

export default GallerySection

Elements style:

import styled from 'styled-components';

export const GalleryContainer = styled.div`
    display: grid;
    gap: 0px;
    width: 100%;
    grid-template-columns: repeat(3, 1fr);
    
    @media screen and (max-width: 982px) {
        grid-template-columns: 1fr 1fr;
    }
`

export const ImageHolder = styled.div`
    display: flex;
    width: 100%;
    position: relative;
    top: 0;
    border: 1px solid #e0bf26;
    cursor: pointer;
    transition: all 300ms;

    ::before {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        transition: background 300ms;
    }

    & svg {
        content: '';
        position: absolute;
        color: #e0bf26;
        font-size: 1.6em;
        top: 50%;
        left: 50%;
        transform: translate(-50%, 50%);
        opacity: 0;
        transition: all 300ms;
    }

    :hover {
        ::before {
            background: #0008;
        }
        & svg {
            opacity: 1;
            transform: translate(-50%, -50%);
        }
    }
`

export const GalleryImage = styled.img`
    width: 100%;
`

Vue CoreUI CDatatable horizontal scroll with too many columns

I’m using Vue CoreUI admin template for a project, and I have a CDataTable. However, I have too many columns and instead of squishing them like you see in the screenshot, I’d like to have a horizontal scroll and just scroll to the right to see the other columns.

Any advice? Here is my code and the screenshot of what it looks like right now.

Code:

<template>
  <div>
    <CCard v-if="tableFields.length > 0">
      <CCardHeader>
        <slot name="header">Inventory list of vehicles</slot>
      </CCardHeader>
      <CCardBody>
        <CDataTable
          :fields="tableFields"
          :items="tableItems"
          :striped="true"
          :items-per-page="10"
          :fixed="true"
          :clickable-rows="true"
          table-filter
          sorter
        >
        </CDataTable>
      </CCardBody>
    </CCard>
  </div>
</template>

Screenshot:
DataTable screenshot

JavaScript – Check every element of 2D arrays for match

I am trying to compare an array of elements with the elements of a 2D array. If there is a match found, then the count for that row of 2D elements will increase. I managed to do it with the first row of 2D array however I do not know how to make the code keep checking for the next row of the 2D array.

var fruits=[
        ['apple', 'banana', 'mango'],
        ['grape', 'pineapple', 'blueberry'],
        ['strawberry', 'mangosteen']
];

var fruit_i_like=[
        ['grape', 'banana', 'pineapple']
];

//if found match from the first row of fruits, increment this var
var fruit1_count = 0;

//if found match from the second row of fruits, increment this var
var fruit2_count = 0;

//if found match from the third row of fruits, increment this var
var fruit3_count = 0;

for (var i = 0; i < fruit_i_like.length; i++) {
        for (var j = 0; j < fruits.length; j++){
            if (fruits[j].indexOf(fruit_i_like[i]) > -1) {
                fruit1_count++;
            }
            
        }
}

The expected result should be printing the number of match the fruit_i_like array has with every rows of the array fruits. For example, here fruit1_count would be 1, fruit2_count would be 2, fruit3_count would be 0.

Is there any way of checking the other rows, using pure JS? Thank you!

html javacsript how to change background image of section while on hover?

hey guys i am new to javascript and i am trying to figure out how to change the background image of my section while hovering the respective texts. currently i want to load 3 different backgrounds but i have issues trying to figure out. below is the code im using .do lmk if u have any suggestions. thanks in advance .

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>3d model</title>
  <style>
    @import url('https://fonts.googleapis.com/css2?family=Krona+One&display=swap');
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    /* custom webkit scrollbar
     */
    
    html {
      -ms-scroll-snap-type: y mandatory;
      scroll-snap-type: y mandatory;
    }
    
    body {
      overflow-x: hidden;
      font-family: 'Krona One', sans-serif;
      background-color: rgb(0, 0, 0);
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
    
    canvas {
      position: fixed;
      top: 0;
      left: 0;
      z-index: -1;
      pointer-events: none;
    }
    
    .section {
      width: 100%;
      height: 100vh;
      display: grid;
      place-items: center;
      scroll-snap-align: center;
      user-select: none;
    }
    
    h1 {
      font-weight: 500;
      font-size: 5vw;
      text-transform: uppercase;
      color: white;
      line-height: 100%;
      text-align: center;
    }
    
    h2 {
      font-weight: 500;
      font-size: 6vw;
      text-transform: uppercase;
      -webkit-text-stroke: 1px white;
      color: transparent;
    }
  </style>
</head>
<section class="section">
  <h1 id="gold">Gold</h1>

  <h2 id="silver">Silver</h2>
  <h1 id="blue">Light Blue</h1>
</section>


</body>

</html>

Clarification on a .reduce() method in my code

 const els = {
    scoreInEl: null, //number <input>
    maxInEl: null, //number <input>
    percentInEl: null, //number <input>
    percentEl: null, //Output
    gradeEl: null, //Output
    scoreUp: null, //Output
    scoreDown: null, //Output
    percentOut: null //Output
  };
    
  Object.keys(els).reduce((o, k) => (o[k] = document.querySelector("#" + k), o), els); //point of interest

So I have this code here that deals with the .reduce() method and I would like further information about my specific case.

I understand the the Object.keys takes each and every name of the element, such as scoreUp

So if you look at MDN documentation on this it says that you take the last element and the first element and that would be o and k.

Does the o[k] make the scoreUp: null; equal something, and what does it make it equal.

I don’t think I understand anything in the query selector, or what the any of the o or k mean in: document.querySelector("#" + k), o,), els) but I do understand that the # means a css id and that the els is the object itself, and in this case would be the initial value.

Doing a console.log(Object.keys...) returns a bunch of confusing information, but from what I can tell its similar to doing something like console.log(document.getElementById()

What I really want from this is an answer to my questions, or a better source than the MDN to explain it

how to put the checkbox to the middle ? now the checkbox is skewed?

I am newbie with html css and javascript and here is my problem.

I code a very simple code like this:

the index.html code:

        <div class="search-btn">
        <i class="search-icon ti-search fa fa-search"></i>
        </div>


        <input type="checkbox" name="" id="nav-mobile-input">
        <div class="nav__overlay"></div>

        <!-- navigation for mobile -->
        <ul id="nav__mobile">
            <div class="nav__mobile-close">
                <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="times" class="svg-inline--fa fa-times fa-w-11" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352 512"><path fill="currentColor" d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"></path></svg>
            </div>
            <li><a href="#" class="nav__mobile-link">Home</a></li>
            <li><a href="#band" class="nav__mobile-link">Bane</a></li>
            <li><a href="#tour" class="nav__mobile-link">Tour</a></li>
            <li><a href="#contact" class="nav__mobile-link">Contact</a></li>
        </ul>

in the styles.css, i code to hide the nav__mobile, using transform like this

#nav__mobile {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: 320px;
max-width: 100%;
background-color: #fff;
transform: translateX(-100%);
}

so it hided the nav__mobile.

My problem is, when it displayed the checkbox, it is skewed as you can see in this picture.
picture about my problem

So, could you please tell me why it happened? And how to solve this problem ? I want the check box to be the middle. Thank you very much for your time.

How do you read a json parsed PDO error message?

From an Ajax function i’m running a php function that does a simple insert to a mysql table.

If it has no issues i just return a 1 and if it has an error it is caught by an exception and returns a json_encode($ex). Since the ajax function has a dataType of “json” it’s all good, except i get this in my answer variable:

    {
      "errorInfo": [
        "23000",
        1062,
        "Duplicate entry 'a' for key 'usuarios.usuario'"
      ]
    }

And it looks good but if i try something like console.log(answer["errorInfo][1]); to try to get just the code error i get some undefined errors and whatnot.

How can i access, individually, those 3 indexes inside of the errorInfo key?

How to access array objects from JS Object and iterate over each objects using EJS

I am having trouble getting my front-end to render the way I want it to. I am trying to render the last five of a array that I have gotten from my mongodb into the front-end for the user to see. below is the code for the back-end and front-end.

front-end

<div class="col-sm-12 mt-5 pb-3">
  <div class="account-purchases">
    <div class="user-info-title pb-4">
      <h1 class="h5"><i class="fas fa-shopping-cart"></i> Purchases</h1>
    </div>
    <div class="user-info-content d-grid gap-5">
      <ul>
        <% for(let i=0; i< 5; i++){ %>
        <li>Order: <%= purchases %>; Duration: <%=duration%></li>
        <% } %>
      </ul>
      <form action="/profile/purchased-items/:id" method="post">
        <button class="btn btn-dark btn-sm" type="submit">
          Download your purchases.
        </button>
      </form>
    </div>
  </div>
</div>

and here is the backend.

back-end

router.get("/", function (req, res) {
  console.log("THE ROUTE WAS FINALLY HIT n");
  if (req.isAuthenticated()) {
    // QUERY FOR ORDERS
    let id = req.user.id;
    User.findById(id, (err, foundUser) => {
      if (foundUser) {
        let navbarLoggedIn = "partials/loggedIn-navbar.ejs";
        let dateObj = req.user.createdAt;
        let createdDate = dateObj.toString().slice(4, 16);
        // PURCHASE ARRAY *WORK ON THIS TOMORROW*
        var array = foundUser.purchases;
        for (let i = 0; i < array.length; i++) {
          var newObject = array[i];
        }
        let purchasedOrder = newObject && newObject["order"];
        let purchasedDuration = newObject && newObject["amount"];

        res.render("profile", {
          purchases: purchasedOrder,
          duration: purchasedDuration,
          currentUser: req.user.username,
          currentCompany: req.user.company,
          currentLocation: req.user.location,
          currentPosition: req.user.position,
          memberStatus: createdDate,
          navbar: navbarLoggedIn,
        });
      }
    });
  } else {
    res.redirect("login");
  }
});

How it renders.
enter image description here
I would like to figure this out before splitting the code into controllerJS files. If you have any insight all will be grateful. Thank you.

JavaScript get class name of label when radio button submitted

I am trying to create a form in JS and if someone selects and submits a radio button, I want to be able to see the class name of the label.

<form id="quizForm" action="#" method="POST" class="form-class">
        
    <p>First Question</p>
    
    <input class="answer" type="radio" name="question-1" value="correctAnswer">
    <label class="RightAnswer">Anwser 1</label>

    <input type="submit" value="SUBMIT">

However when I try to use JS to get the class name or id of the label it gives the the info of the form not the label of the selected radio button.

window.onload = pageReady;

function pageReady(){

    var formHandle = document.forms.quizForm;
    console.log(formHandle);

    formHandle.onsubmit = processForm;

    function processForm(){
        var questionOne = document.querySelector('input[name="question-1"]:checked');
        var correctAnswerOne = document.getElementById("correct-answer-1")
        console.log(questionOne.value);

        console.log(this.id);
        console.log(this.className)
}

Discord.js Member Join guildMemberAdd issue

I have a events handler that runs through a file called “events” that I found on the discord.js website. It appears as so, taking files from the event folder and calling them if they occur:

// creates an array of files from the commands file
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
    const event = require(`./events/${file}`);
    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args));
    }
    else {
        client.on(event.name, (...args) => event.execute(...args));
    }
}

An example of one of the events that works is one that is called when a channel is created:

module.exports = {
    name: 'channelCreate',
    execute(channel) {
        console.log(`${channel.name} was created`);
        console.log(channel.id);
    },
};

However, when I try calling the addGuildMember event, which should occur when a member joins, it simply doesn’t work. Nothing shows up in the console and it doesn’t recognize a person has joined.

module.exports = {
    name: 'guildMemberAdd',
    execute(member) {
        console.log('member joined');
        console.log(member);
    },
};

What am I doing wrong? I tried looking if guildMemberAdd was deprecated, but apparently it’s still used, has anybody successfully added this event with an event handler?

tab menu corresponding button active

Hello I am making a tab menu right now.
My problem is that I want to give is-active when the button is clicked, but I don’t know what value to put in the empty space there.


type Props = {
  title: string
  index: number
  setSelectedTab: (index: number) => void
}

const TabTitle: React.FunctionComponent<Props> = ({ title, setSelectedTab, index }) => {
  
  // The value to be activated. Initial value is `0th button`
  const [activeIndex, setActiveIndex] = useState(0);
  

  const onClick = useCallback(() => {
    setSelectedTab(index)
  }, [setSelectedTab, index])


  return (
    <li>
      <button
      key={index}
      className={activeIndex === [empty place] ? "is-active" : ""} 
      onClick={() => onClick()}
      >
        {title}
        </button>
    </li>
  )
}
 console.log(index);
  // 0
  // 1 
  // 2 

How to use the index value If you click the 0th button, index : 0
If ​​you click the 1st button, index: 1
After making it like this, className={activeIndex === index ? "is-active" : ""} If you put index , it will work normally, but I don’t know how to make an index like that.

How can I set the index to give first click 0 second click 1 ​according to the clicked value?