Home > Mobile >  React - Issue with button onClick for void array
React - Issue with button onClick for void array

Time:08-24

  • I can't get void values from buttonAction array void for button onClick.

  • I can get the length value in the array correctly. but I can't get the array value at all.

  • Can anyone help me see the error? Thanks.

Navbar.tsx

<div className="items">
<Popup 
show={true} 
title={"Popup"} 
buttonText={["Button1","Button2"]} 
buttonAction={() => [redirect(), redirect2()]} >
</Popup>
</div>

Popup.tsx

import React from "react";

//styled
import {Area} from "./index.styled"

import Button from "../button";

type Props = {
    show: boolean;
    title?: string;
    desc?:string;
    buttonText:string[];
    buttonAction:() => void[];
}

const Popup: React.FC<Props> = (props) => {
    if (!props.show) return null;
    return (
        <Area>
            <div className="content">
                {props.title && <h3 className="title">{props.title}</h3>}
                {props.desc && <p className="desc">{props.desc}</p>}
                <>
                    {props.buttonAction().map((value:void, index, array) => {
                        return(
                            <Button primary key={index} onClick={() => {value}}>
                                {index}
                            </Button>
                        )
                    })}
                </>

            </div>
        </Area>
    )
}

export default Popup;

CodePudding user response:

() => void is just the typing for a function with no parameters that returns nothing. You presumably want to map these to your button clicks.

I recommend adjusting your code as follows:

Create a type for your popup buttons, eg. PopupButton. Each button has a text and an action.

type PopupButton {
    text: string;
    action: () => void;
}

Now change your props to accept PopupButtons

type Props = {
    show: boolean;
    title?: string;
    desc?:string;
    buttons: PopupButton[];
}

And finally map the props.buttons data to your Button components and bind their action/text.

<>
    {props.buttons.map((button, index) => {
        return(
            <Button primary key={index} onClick={button.action}>
                {button.text}
            </Button>
        )
    })}
</>

Understand that:

  • A new type was created to define the data needed for each button (text and action)
  • The type of action is () => void, ie. a parameterless function with no return type
  • action was bound to the onClick
  • Related