'How can I pass props from one component to another in typescript?
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
}
Solution 1:[1]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ergis |
