react – not able to setValue for input box

I am making 2 otp input in my application.

In Input.tsx, I am using react-otp-input for the otp functionality
if

    <OtpInput
      value={"abcde"}
      ...
      numInputs={5}
    />

The UI of react-otp-input will be
enter image description here

Now the problem is, when I try to change the value of otp, it throws error

Cannot set properties of undefined (setting 'value')

How can I fix it?

Input.tsx

import React, { useState } from "react";
import OtpInput from "react-otp-input";

type InputPropType = {
  value: string;
  setValue: (event: string) => void;
};

function Input(props: InputPropType): JSX.Element {
  const { value, setValue } = props;
  return (
    <OtpInput
      value={value}
      onChange={(e: string) => {
        setValue(e);
      }}
      numInputs={5}
    />
  );
}

export default Input;

App.tsx

import React, { useState } from "react";

import Input from "./Input";

export default function App() {
  type InputValueType = {
    id: number;
    value: string;
  };
  const [inputValues, setInputValues] = useState<Array<InputValueType>>([
    { id: 0, value: "" },
    { id: 1, value: "" }
  ]);

  const InputGroup = () => {
    let numOfInputs: number = 2;
    var rows: Array<any> = [];
    for (var i = 0; i < numOfInputs; i++) {
      let inputValue: InputValueType = inputValues[i];
      rows.push(
        <Input
          key={inputValue.id}
          value={inputValue.value}
          setValue={(event: string) => {
            let inputValuesTemp = inputValues;
            inputValuesTemp[i]["value"] = event;
            setInputValues(inputValuesTemp);
          }}
        />
      );
    }
    return <>{rows}</>;
  };

  return (
    <div className="App">
      <InputGroup />
    </div>
  );
}

Codesandbox
https://codesandbox.io/s/react-typescript-forked-s38ck9?file=/src/App.tsx:0-918

Regular expression not giving me expected result

I am wanting to sort an array using regular expression such that after the array is sorted, all the dishes are included in results including both matched and unmatched ones. Currently only few matched ones are in the sorted array. If I have two words to be search in regular expression then it should search all the two words independently and finally get the matched items as well as unmatched items. If i search for ‘Fish CUrry’ then it should look for both words independently and get the results and also add all the unmatched results at the end of sorted array. Here unmatched is ‘Biryani’ and all other are matched.

let allDishes =     [
        {
            "DishId": 66,
            "DishName": "Fish CUrry",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 65,
            "DishName": "Fish CUrry Masala",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 64,
            "DishName": "Chilli Fish CUrry Masala",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 63,
            "DishName": "Mutton CUrry",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 62,
            "DishName": "Biryani",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        }
    ]

Below is the code that I have written:

let value = 'Fish CUrry';
let regex = new RegExp(`^${value}`, `i`);
const sortedArr = allDishes 
                 .filter(x=>regex.test(x.DishName))
                 .sort((a, b) =>a.DishName.localeCompare(b.DishName));

Current result from above code is below:

[
    {
        "DishId": 66,
        "DishName": "Fish CUrry",
        "DateCreated": "2021-10-21T11:19:28.000Z",
    },
    {
        "DishId": 65,
        "DishName": "Fish CUrry Masala",
        "DateCreated": "2021-10-21T11:19:28.000Z",
    }
]

Expected sorted result needed should look like below:

[
        {
            "DishId": 66,
            "DishName": "Fish CUrry",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 65,
            "DishName": "Fish CUrry Masala",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 64,
            "DishName": "Chilli Fish CUrry Masala",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 63,
            "DishName": "Mutton CUrry",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 62,
            "DishName": "Biryani",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        }
    ]

Unity WebGL Build Particle System Error On Safari

So I have a small web game that I made recently, and decided to try it out in Safari. Every other browser works (Chrome, Firefox, Edge), but a few seconds (seemingly random) after an on screen particle system starts playing, the whole game crashes. Obviously disabling particles isn’t an option. Any ideas?

An error occurred running the Unity content on this page. See your browser JavaScript console for more info. The error was:
RuntimeError: Out of bounds memory access (evaluating 'asm[name].apply(null, arguments)')
<?>.wasm-function[OptimizedPolynomialCurve::Evaluate(math::_float4 const&) const]@[wasm code]
<?>.wasm-function[Evaluate(MinMaxCurve const&, math::_float4 const&, math::_float4 const&)]@[wasm code]
<?>.wasm-function[ParticleSystem::UpdateModulesPreSimulationIncremental(ParticleSystemUpdateData const&, ParticleSystemParticles&, unsigned long, unsigned long, math::_float4 const&, bool)]@[wasm code]
<?>.wasm-function[ParticleSystem::Update1b(ParticleSystemUpdateData&, int)]@[wasm code]
<?>.wasm-function[ParticleSystem::UpdateFunction(ParticleSystemUpdateData*)]@[wasm code]
<?>.wasm-function[ParticleSystem::BeginUpdateAll()]@[wasm code]
<?>.wasm-function[ParticleSystem::InitializeClass()::PreLateUpdateParticleSystemBeginUpdateAllRegistrator::Forward()]@[wasm code]
<?>.wasm-function[ExecutePlayerLoop(NativePlayerLoopSystem*)]@[wasm code]
<?>.wasm-function[ExecutePlayerLoop(NativePlayerLoopSystem*)]@[wasm code]
<?>.wasm-function[MainLoop()]@[wasm code]
<?>.wasm-function[dynCall_v]@[wasm code]
wasm-stub@[wasm code]
81288@[native code]
@http://localhost:55812/Build/dev.framework.js:1043:25
browserIterationFunc@http://localhost:55812/Build/dev.framework.js:8963:17
callUserCallback@http://localhost:55812/Build/dev.framework.js:7153:7
runIter@http://localhost:55812/Build/dev.framework.js:7214:20
Browser_mainLoop_runner@http://localhost:55812/Build/dev.framework.js:7128:27

Wicket Adding a draggable DialogBox with user defined tetarea, textbox and button

I am pretty new to Apache Wicket. I was able to get a home page, a form accepting inputs and then final success page where all accepted inputs are displayed. When this success page loads, there is a button. I would like to show a draggable dialog box with a textbox or a text area with when the button is clicked. I was trying to execute the JQuery extensions for wicket. But not able to get it on to my success page. It always complains for wicket id or component not exist and errors related based on what has been written on the java code or added to the markup html file. Here is the code to call the draggable dialogbox i created..Yes I wrote the wicket:extend for subclass. Still very confusing to me..please help.

This code is inside the AjaxButton Click...
HomePanel homepanel = new HomePanel("homepanel");
homepanel.setOutputMarkupId(true);
homepanel.setOutputMarkupPlaceholderTag(true); //tried removing it
homepanel.getMarkupId(true);  //just for trial i put here
homepanel.setVisible(true); 
add(homepanel);
homepanel.setVisible(true);
target.add(homepanel); 

Using apache wicket version 8.x
What am I do do. I am tapped out and no other way as my search also returns same thing .. any help.. thanks for the same.

console.log script returns “Wrong channel!”

I’m setting up a Discord bot, and I want it to send a message to the main channel of my server when I type node .. I typed:

client.on('ready', () => {
  const Channel = client.channels.cache.get('<My.General.Channel.ID#>');
  if (!Channel) return console.log('Wrong channel!');
  else Channel.send('I am here');
});

I get “Wrong channel!”. I should just insert the channel ID number, right? I’ve directly pasted from Discord’s “Copy ID” and still get a problem.

node.js puppeteer “document is not defined”

I am attempting to try click a button using code without an id or class, but my terminal always responds with:

document.getElementsByTagName("Accept Cookies");
    ^

ReferenceError: document is not defined

This is my code:

const puppeteer = require('puppeteer');

const product_url = "https://www.nike.com/launch"

async function givePage() {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    return page;
}

async function acceptCookies(page) {
    await page.goto(product_url);
    const btn = await page.waitForSelector('#cookie-settings-layout > div > div > div > 
div:nth-child(3) > div.ncss-col-md-6.ncss-col-sm-12.mb5-sm > button')
    await btn.click()
}

async function notifyMe(page) {
    await page.goto(product_url);
    document.querySelector("button[type="submit"]").click("Notify Me");
}

async function checkout() {
    var page = await givePage();
    await acceptCookies(page);
    await notifyMe(page);
}

checkout();

What did I do wrong and how can I fix this?

Firebase createUserProfileDocument() is returning undefined

As the title says, the createUserProfileDocument() method from firebase is returning undefined for some reason, therefore, it’s throwing an error on my broswer’s console.

The error that is being thrown is: App.js:23 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onSnapshot') at App.js:23:1

Please find the code below:

import './App.css';
import { connect } from 'react-redux';
import { Switch, Route } from 'react-router-dom';
import HomePage from './pages/homepage/homepage.component';
import ShopPage from './pages/shop/shop.component';
import Header from './components/header/header.componet';

import { auth, createUserProfileDocument } from './firebase/firebase.utils';
import SignInAndSignUpPage from './pages/sign-in-and-sign-up/sign-in-and-sign-up.component';
import { setCurrentUser } from './redux/user/user.actions';

class App extends React.Component {
    unsubscribeFromAuth = null;

    componentDidMount() {
        const { setCurrentUser } = this.props;

        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
                console.log(userRef);
                userRef.onSnapshot((snapshot) => {
                    setCurrentUser({
                        id: snapshot.id,
                        ...snapshot.data(),
                    });
                });
            }
            setCurrentUser(userAuth);
        });
    }

    componentWillUnmount() {
        this.unsubscribeFromAuth();
    }

    render() {
        return (
            <div className='App'>
                <Header />
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route exact path='/shop' component={ShopPage} />
                    <Route
                        exact
                        path='/signin'
                        component={SignInAndSignUpPage}
                    />
                </Switch>
            </div>
        );
    }
}

const mapDispatchToProps = (dispatch) => ({
    setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});

export default connect(null, mapDispatchToProps)(App);

The portion of code related to my error is the following:

componentDidMount() {
        const { setCurrentUser } = this.props;

        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
                console.log(userRef);
                userRef.onSnapshot((snapshot) => {  // This is Line 23......
                    setCurrentUser({
                        id: snapshot.id,
                        ...snapshot.data(),
                    });
                });
            }
            setCurrentUser(userAuth);
        });
    }

I console.logged(userRef) as you can see, and it returns undefined. This is my first experience with firebase so I am not sure where the error is.

I googled and found an answer here in stackoverflow which is alike to my issue: TypeError: Cannot read properties of undefined (reading ‘onSnapshot’)

However, that problem is specifically related to how the developer was passing the method as an array and not a method, which does not help my situation.

Please don’t downvote my question in case of finding it wrong, please suggest edits instead, since I am kind of new to stackoverflow and a complete noob to firebase.

Thanks a lot in advance for your help!

Attempting to make Ray Tracing inside of p5.js but function recursion is acting weird

So, I found a source online that went over ray tracing for c++ (https://www.scratchapixel.com/code.php?id=3&origin=/lessons/3d-basic-rendering/introduction-to-ray-tracing)

I decided to go into p5.js and attempt to replicate what they have in their source code, but ran into an error when I got to function recursion. To add reflections they used recursion and ran the same function again, but when I attempt the same thing I get all sorts of incorrect outputs… This is my code:
https://editor.p5js.org/20025249/sketches/0LcyoY8yS

function trace(rayorig, raydir, spheres, depth) {
  let tnear = INFINITY;
  let sphere;
  
  // find intersection of this ray with the spheres in the scene
  for (let i = 0; i < spheres.length; i++) {
    t0 = INFINITY;
    t1 = INFINITY;
    if (spheres[i].intersect(rayorig, raydir)) {
      if (t0 < 0) t0 = t1;
      if (t0 < tnear) {
        tnear = t0;
        sphere = spheres[i];
      }
    }
  }
  
  // if there's no intersection return black or background color
  if (!sphere) return createVector(2, 2, 2);
  
  let surfaceColor = createVector(0); // color of the ray/surfaceof the object intersected by the ray
  let phit = createVector(rayorig.x, rayorig.y, rayorig.z).add(createVector(raydir.x, raydir.y, raydir.z).mult(tnear)); // point of intersection
  let nhit = createVector(phit.x, phit.y, phit.z).sub(sphere.center); // normal at the intersection point
  nhit.normalize(); // normalize normal direction
  
  // If the normal and the view direction are not opposite to each other
  // reverse the normal direction. That also means we are inside the sphere so set
  // the inside bool to true. Finally reverse the sign of IdotN which we want
  // positive.
  let bias = 1e-4; // add some bias to the point from which we will be tracing
  let inside = false;
  if (createVector(raydir.x, raydir.y, raydir.z).dot(nhit) > 0) {
    nhit = -nhit;
    inside = true;
  }
  
  if ((sphere.transparency > 0 || sphere.reflection > 0) && depth < MAX_RAY_DEPTH) {
    let facingratio = createVector(-raydir.x, -raydir.y, -raydir.z).dot(nhit);
    // change the mix value to tweak the effect
    let fresneleffect = mix(pow(1 - facingratio, 3), 1, 0.1);
    // compute reflection direction (not need to normalize because all vectors
    // are already normalized)
    let refldir = createVector(raydir.x, raydir.y, raydir.z).sub(createVector(nhit.x, nhit.y, nhit.z).mult(2).mult(createVector(raydir.x, raydir.y, raydir.z).dot(nhit)));
    refldir.normalize();


    // Here is the error:
    let reflection = trace(createVector(phit.x, phit.y, phit.z).add(createVector(nhit.x, nhit.y, nhit.z).mult(bias)),
                           refldir,
                           spheres,
                           depth+1
                          );


    let refraction = createVector(0);
    // // if the sphere is also transparent compute refraction ray (transmission)
    // if (sphere.transparency) {
    //   let ior = 1.1
    //   let eta = (inside) ? ior : 1 / ior; // are we inside or outside the surface?
    //   let cosi = createVector(-nhit.x, -nhit.y, -nhit.z).dot(raydir);
    //   let k = 1 - eta * eta * (1 - cosi * cosi);
    //   let refrdir = createVector(raydir.x, raydir.y, raydir.z).mult(eta).add(createVector(nhit.x, nhit.y, nhit.z).mult(eta *  cosi - sqrt(k)));
    //   refrdir.normalize();
    //   refraction = trace(createVector(phit.x, phit.y, phit.z).sub(createVector(nhit.x, nhit.y, nhit.z).mult(bias)),
    //                      refrdir,
    //                      spheres,
    //                      depth + 1
    //                     );
    // }
    // the result is a mix of reflection and refraction (if the sphere is transparent)
    surfaceColor = (
      createVector(reflection.x, reflection.y, reflection.z)
        .mult(fresneleffect)
        .add(
          createVector(refraction.x, refraction.y, refraction.z).mult(1 - fresneleffect).mult(sphere.transparency)
        )
    )
    .mult(sphere.surfaceColor);
  }
  return createVector(surfaceColor.x, surfaceColor.y, surfaceColor.z).add(sphere.emissionColor);
}

The error is that the reflections don’t give me the same output as the c++ script and seems to be wonky. I cannot for the love of me figure out why the recursive function just doesn’t work.

I have attempted to run it without the recursion and it worked perfectly fine but the recursion is where is breaks

The way I found the error was by printing on the original c++ script and printing on the one I was making and it all works up until the recursive reflections. I get the correct first output but then it all goes down hill.

Their outputs:

[-0.224259 3.89783 -19.1297]
[-0.202411 3.88842 -19.0835]
[-0.180822 3.88236 -19.0538]

My outputs:

[-0.224259 3.89783 -19.1297] // correct
[-0.000065 0.001253 -0.005654] // incorrect
[-0.000064 0.00136 -0.00618] // incorrect

Summary: I made a function that works but the recursion breaks it and I cannot figure out why

Unable to assign a variable as a arithmetic operator in javascript while making a calculator

Hello I was making a calculator
But i am unable to play arithmetic operators in it please solve it. because it was not checking it as a arithmetic operator it was checking it as string. And if i assisgn + like this var a = + ; it gives me an error that unexpected token }

Html code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <ulnk rel="stylesheet" href="css/index.css">
  <script src="js/index.js"></script>
  <title>CALCULATOR </title>
</head>
<body>
<!------------------------------------------->

<input readonly="true" type="text" id="value"></input>
<button id="result" ></button>

<ul><button onclick="one()" >1</button></ul>    
<ul><button onclick="four()" type="submit">4</button></ul>
<ul><button onclick="seven()" type="submit">7</button></ul>
<ul><button onclick="zero()" type="submit">0</button></ul>
<ul><button onclick="Add()" type="submit">+</button></ul>
<ul><button onclick="RESULT()" type="submit">=</button></ul>
<!------------------------------------------->
</body>
</html>

Js code

function one() {
var value = document.getElementById("value")
var input = value.value +="1"

}
function RESULT() {
var value = document.getElementById("value")
var input = value.value
var result = value.value
}
function Add() {
var value = document.getElementById("value")
var input = value.value +='+'
}
function four() {
var value = document.getElementById("value")
var input = value.value +=4
}
function seven() {
var value = document.getElementById("value")
var input = value.value +=7
}
function zero() {
var value = document.getElementById("value")
var input = value.value +=0
}
function RESULT() {
var result = document.getElementById("result")
var value = document.getElementById("value").value
var results_value =parseInt(value);
var results_value2 = result.innerHTML=results_value
}

HTML JS trigger button enter

Was trying to get this working that I saw from another post here. I got it working but I can get the enter to work. I tried to tie in https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter but for the life of me cant get both to work.

Hope someone can help!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

    $('#button').click(function(e) {  
        var inputvalue = $("#input").val();
        window.location.replace(" http://www.example.com/page/"+inputvalue);

    });
});
</script> 
</head>
<body>

       <input type="text" value="11" id="input"> 
       <button type="button" id="button">Click Me!</button>
</body>
</html>

Get value from few Select in Material-UI

I have two MUI Select components on my page. I’m trying to set values depends on id of Select. I’ve checked (id === “breed-select”) in console and (at first) it’s true, but immediately after that it become false, and i cant understand why. Where i made a mistake? May be there is a better way to set values of two Select components?

import React from 'react';
import './AddCatPopup.css';
import {Box, Button, FormControl, InputLabel, MenuItem, Select, TextField} from '@mui/material';
import {theme} from '../../theme';
import {ThemeProvider} from '@mui/material/styles';

function AddCatPopup({ breeds, isOpen, onClose, onAddCat }) {

  const breedsName = breeds.map(item => item.nameBreed);

  const colorsArray = [
    'black',
    'white',
    'grey',
    'red',
    'multicolor'
  ];

  const [name, setName] = React.useState('');
  const [price, setPrice] = React.useState(0);
  const [color, setColor] = React.useState('');
  const [age, setAge] = React.useState(0);
  const [breed, setBreed] = React.useState('');

  function handleChange(event) {
    const {
      target: { value, id }
    } = event;
    id === "breed-select" ? setBreed(value) : setColor(value);
  }

  function handleSubmit(e) {
    e.preventDefault();
  }

  return(
    <section className={`popup ${isOpen && 'popup_opened'}`}>
      <div className={'popup__container'}>
        <button type="button" className={'popup__close-btn'} onClick={onClose}></button>
        <p className={'popup__title'}>Enter info about cat</p>
        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Name"
                   required />

        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Price"
                   required />

        <FormControl sx={{ mt: 1, mb: 1 }}
                     variant="standard"
                     required>
          <InputLabel id="breed-label">Breed</InputLabel>
          <Select
            labelId="filter-breed"
            id="breed-select"
            label="Breed"
            value={breed}
            onChange={handleChange}
          >
            {breedsName.map((item) => (
              <MenuItem
                key={item}
                value={item}
                id="breed-select"
                onClick={handleChange}
              >
                {item}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <FormControl sx={{ mt: 1, mb: 1 }}
                     variant="standard"
                     required>
          <InputLabel id="color-label">Color</InputLabel>
          <Select
            labelId="filter-color"
            id="color-select"
            label="Color"
            value={color}
          >
            {colorsArray.map((item) => (
              <MenuItem
                key={item}
                value={item}
                id="color-select"
                onClick={handleChange}
              >
                {item}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <TextField sx={{ mt: 1, mb: 1 }}
                   id="standard-required"
                   variant="standard"
                   label="Age"
                   required />

        <ThemeProvider theme={theme}>
          <Button sx={{ mt: 1, mb: 1 }}
                  variant="contained"
                  color={'secondary'}
                  onClick={handleSubmit}>
            Add
          </Button>
        </ThemeProvider>

      </div>
    </section>
  );
}

export default AddCatPopup;

JSON parse in Javascript with [ [duplicate]

I am trying to parse this JSON file. I was able to get temp easy but I am not able to get main from the weather. I assume this is due to the “weather”: [ than normal JSON file.

Does anyone know how to parse this correctly to be able to access the weather.main data.

JSON file:

{
  "coord": {
    "lon": -4.5063,
    "lat": 55.6787
  },
  "weather": [
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 3.72,
    "feels_like": 1.32,
    "temp_min": 3.07,
    "temp_max": 4.94,
    "pressure": 1024,
    "humidity": 75
  }

Here is my current parser:

async function getWeather(lat, lon) {
  const params = new URLSearchParams({
    lat,
    lon,
    units: "metric",
    appid: API_KEY,
  })
  return fetch(`https://api.openweathermap.org/data/2.5/weather?${params}`)
  .then(function (response) {
    return response.json()
  }).then(function (obj) {
    console.log(obj.main.temp)
    weatherTemp = obj.main.temp;
    console.log("OBJ" + obj.weather.main) // does not work, return undefined. Not able to access
    //weatherType = obj.weather.main;
    // print();
    // ContextMerge();
  }).catch(function (error) {
    console.log("Something went wrong" + error)
  });
  }

Nodejs Require is not defined while using reverse shell

If require is not available, to obtain the require by:

process = this.constructor.constructor(‘return (function(){return process})()’)();
var require = process.mainModule.require;

used

shell = ‘process = this.constructor.constructor(‘return (function(){return process})()’)();’

shell += ‘var require = process.mainModule.require;’

Errors: process is not defined
if we add const before process
Errors: mainModule is not defined

How do we import process without Require , and how do we process the code to server

How Can I target single item by map button in React Typescript?

So I have a functional components here:

export default function Test() {
    const [products, setProduct] = useState<any>([]);
    const [image, setImage] = useState<any>([""]);
    const [prices, setPrice] = useState<any>([]);
    const [showPrice, setShowPrice] = useState<boolean>(false);
    const [PhonePrice, setPhonePrice] = useState<any>("");


    useEffect(() => {
        async function loadProducts() {
            const res = await fetch("http://raw.githubusercontent.com/reborn094/Practice/main/data.json", {
                method: "GET",
            });
            const json = await res.json();
            const data = json.products;

            setProduct(data);

    return (
        <div>
                    {products.map((product: any, index: number) => {
                        return (
                            <Col>
                                <Card key={index} style={{ width: "20rem" }}>
                                    <Card.Body>
                                        <Card.Title>
                                        </Card.Title>
                                        <Card.Title>
                                            <Child ProductImage={image[index]} name={product.name} code={product.code}  onSelectProduct={()=>{  
                                             

> 

what should I write here????
------------------------

   
                                            }}
                                            ></Child>
                                           
                                        </Card.Title>
                                        <Card.Text></Card.Text>
                                    </Card.Body>
                                </Card>
                            </Col>
                        );
                    })}
        </div>
    );
}

And here is my Child components :

export default function Child(props:{
    onSelectProduct?:()=> void;
}) {
  return (
      <div>
        <Button onClick={props.onSelectProduct}></Button>
    </div>
  )
}

My question is What if I want to set button in Test components to target single item in list, what should I do? Because Now If I set Button that Button would trigger all item.What should I do in the function onSelectProduct?