I want to pass the onclick method from child to parent using react and typescript.
what I am trying do?
I have a parent component which renders child component and is like below,
function Parent() {
const [isDialogOpen, setisDialogOpen] = useState('');
const set =() => {
setisDialogOpen(!isDialogOpen);
}
return (
<Child size={16} fontSize={12}/>
);
}
interface Props {
size?: number;
fontSize?: number;
}
const Child = styled.div<Props>`
font-size: ${p => (p.fontSize ? p.fontSize + 'px' : '8px')};
size: ${p => (p.fontSize ? p.fontSize + 'px' : '12px')}
`;
export default Child;
Now, how can I add onClick method to the Child component such that it sets the isDialogOpen state?
what I tried?
I was trying to do something like below,
function Parent() {
const [isDialogOpen, setisDialogOpen] = useState('');
const setDialog =() => {
setisDialogOpen(!isDialogOpen);
}
return (
<Child onClick={setDialog} size={16} fontSize={12}/>
);
}
interface Props {
onClick?: () => void;
size?: number;
fontSize?: number;
}
const Child = styled.div<Props>`
font-size: ${p => (p.fontSize ? p.fontSize + 'px' : '8px')};
size: ${p => (p.fontSize ? p.fontSize + 'px' : '12px')}
`;
export default Child;
But how can I add the onClick method to div near this line?
const Child = styled.div<Props>`
font-size: ${p => (p.fontSize ? p.fontSize + 'px' : '8px')};
size: ${p => (p.fontSize ? p.fontSize + 'px' : '12px')}
`;
Just wrap Child component with a function.
const StyledChild = styled.div<Props>`
font-size: ${p => (p.fontSize ? p.fontSize + 'px' : '8px')};
size: ${p => (p.fontSize ? p.fontSize + 'px' : '12px')}
`;
const Child = ({fontSize, size, onClick}: Props) => {
return (
<StyledChild onClick={onClick} fontSize={fontSize} size={size} />
)
}