Home > Mobile >  How can I pass props from one component to another in typescript?
How can I pass props from one component to another in typescript?

Time:02-05

So I have a button ui component, and I need to insert it in another component. I have a button type and interface, which look like this:

type IButton = {
    className?: string,
    onClick?: MouseEventHandler;
    children: React.ReactNode;
    props: IButton;
}

interface ButtonProps{
  props: IButton;
}

And Button looks like this:

export const Button = ({props}: ButtonProps) => {
  return (
    <button 
    className={`btn ${props.className}`}
    onClick={props.onClick}
    >
       {props.children}
    </button>
  );

So I should pass props through props interface. And in another component I use the button:

<Button onclick={() => console.log('error')}></Button>

But from here on I don't know how I should pass the props. I tried making onClick() function but I get an error:

Property 'props' is missing in type '{ onclick: () => void; }' but required in type 'Pick<ButtonProps, "props">

Edit: I also have propTypes:

Button.propTypes = {
    onclick: PropTypes.func
}

CodePudding user response:

I believe this is what you are after:

interface ButtonProps {
  className?: string;
  onClick?: React.MouseEventHandler;
  children: React.ReactNode;
}

export const Button = ({ className, onClick, children }: ButtonProps) => {
  return (
    <button className={`btn ${className}`} onClick={onClick} type="button">
      {children}
    </button>
  );
};

As you see, you don't need the type IButton, just an interface defining the props of your component.

Using parameter destructuring is quite common when working with react, so I put it like that. You can also do

export const Button = (props: ButtonProps) => {
  return (
    <button className={`btn ${props.className}`} onClick={props.onClick} type="button">
      {props.children}
    </button>
  );
};

Also, note that there is a PropsWithChildren type in react that you can use for this case, which already contains a children property.
You use it like that:

interface ButtonProps {
  className?: string;
  onClick?: React.MouseEventHandler;
  // => no "children" property here
}

export const Button = ({
  className,
  onClick,
  children,
}: PropsWithChildren<ButtonProps> /* note PropsWithChildren here */) => {
  return (
    <button className={`btn ${className}`} onClick={onClick} type="button">
      {children}
    </button>
  );
};

One more thing: it is recommended to give every button a type attribute.

CodePudding user response:

Your error is here: Button = ({props}: ButtonProps) => ...
What you are doing is destructuring the props, which is wrong in this case.

Should be: Button = (props: ButtonProps) => ... (without the curty brackets).

  •  Tags:  
  • Related